Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top