0

So the problem is the following: I have an action method that returns json. What I need to do is use that json to construct some html based on it. For example lets say I receive a list of cars. What I want to do is display the list like this for example:

<div id="cars">
@foreach(var car in Model)
{
  <p>car.Name</p>
}
</div>

<div id="pageLinks">
  @Html.MyPageLinks(Model.PageInfo)
</div>

Currently this is a view and what I do is render that view in the controller and return the whole result as json result (check this link). Everything works great, however there is one major drawback - the action method is not testable, as I have to mock tons of things in order to make the FindPartialView to work (and currently I am stuck with this). Even worse, I have coupled the view with the action, i.e. changes to the view will also harm the unit tests and this is not acceptable.

On the other hand using javascript to generate all that html seems a very bad approach, since it is going to be a lot of raw javascript and jquery (keep in mind that even in my simplified example there will be a lot of js and I will loose the option to test MyPageLinks since everything will be js).

What I need/want to do is return only json (just the data objects, no html) and in the view to have something like a template that will be applied once the json is returned.

Community
  • 1
  • 1
Unknown
  • 1,377
  • 1
  • 15
  • 33

1 Answers1

1

Simply return HTML, not JSON from your controller action. So put the view snippet you have shown into a partial wrapped inside a div:

<div id="paginatedCars">
    @Html.Partial("Cars")
</div>

and then have the controller action that you are invoking return this updated partial.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I didn't quite get this. The page uses ajax requests, example: the first action method is a normal ViewResult and it displays all the data needed to make a search. The search button however invokes some js, which connects to the server and invokes the second action method, which is a JsonResult, and asynchronously updates the first View. – Unknown Sep 12 '12 at 09:33
  • That's not a problem - you trigger the AJAX request to a controller action that returns a `PartialView` and in the success callback of your AJAX request you simply refresh the DOM: `$('#paginatedCars').html(result)` where `result` is obviously the partial HTML returned by your controller action that you invoked with AJAX. You don't need any JSON for this case. – Darin Dimitrov Sep 12 '12 at 09:33
  • I am a complete idiot. Overcomplicating things seems to be a serious drawback when developing :). Thank you a lot for the help. – Unknown Sep 12 '12 at 09:50