Reputation: 7105
Within my first real MVC application, I'm running into this with nearly every page. I'm sure I'm missing something.
An example I'm currently dealing with:
The page has multiple dropdowns (filters) and a grid. I've got razor code that populates the filters, and the grid initially using a view model for the data. All is well, code is clean and the page loads perfectly.
Now, when I select a different filter option, this may change some of the other dropdowns, and will certainly change the data in the grid. So I'm making an ajax call to one of my controller methods to get the new data. I then have to rebuild the grid in JS along with any dropdowns that have changed. This is just duplicating what the Razor code does for the initial page load.
If I've added classes, attributes, etc to anything in Razor, this also must be duplicated in JS.
There must be a pattern I'm missing. At this point I don't even care if the updating is done dynamically with ajax. If I can do all of it in Razor with 'postbacks' somehow that's fine to. Anything to avoid this massive code duplication.
Upvotes: 2
Views: 425
Reputation: 63522
You could create a PartialView
that does exactly what your initial page load does.
public ViewResult Details(int id)
{
DetailsModel model = new DetailsModel...
return View(model);
}
In the above case you could have FilterModel
be a member of DetailsModel
, either way, you can create a partial action method if you need to crunch some data on what to present:
public PartialViewResult Filters(int someParams...)
{
FilterModel model = new FilterModel...
return PartialView("Filters"
}
and then call it from your View like this:
<div id="filters">
@Html.Action("Filters", someParams)
</div>
or this if FilterModel
is a member of DetailsModel
:
<div id="filters">
@Html.Partial("Filters", Model.FilterModel)
</div>
and when you need to update it on the client side you can request that partial again:
var filterUrl = "@Html.ActionLink("Filters")";
$(...).change(function(){
$("#filters").load(filterUrl);
});
Upvotes: 2