Reputation: 789
I have a view model in my ASP.NET MVC application:
public class FiltersViewModel
{
public IEnumerable<SelectListItem> AvailableFilters { get; set; } // fills a drop down menu
public IList<TechnologyFilter> TechnologyFilters { get; set; }
public IList<ContractTypeFilter> ContractTypeFilters { get; set; }
public FiltersViewModel()
{
this.TechnologyFilters = new List<TechnologyFilter>();
this.ContractTypeFilters = new List<ContractTypeFilter>();
}
}
Then in my controller I pick up the selected value from the dropdown menu and create a specific filter object (Technology or ContractType filter) and then return the View, where I have the following code:
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.DropDownListFor(m => m.SelectedFilterId, Model.AvailableFilters)
if (Model.TechnologyFilters != null)
{
@for (int i = 0; i < Model.TechnologyFilters.Count; i++)
{
<div id="technologyFilter">
@Html.HiddenFor(m => m.TechnologyFilters[i].Name)
@Html.DisplayFor(m => mTechnologyFilters[i].Name)
</div>
}
}
}
If the HTML markup is done in this way and the viewmodel is posted back from the server, the viewmodel fills the TechnologyFilters list correctly. But when I extract the for loop in a partial view, the data stops being posted back correctly and my TechnologyFilters list is empty:
The same view, but this time calling partial view:
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.DropDownListFor(m => m.SelectedFilterId, Model.AvailableFilters)
if (Model.TechnologyFilters != null)
{
Html.RenderPartial("_TechnologyFilters", Model.TechnologyFilters);
}
_TechnologyFilters.cshtml partial view:
@model List<MVCFilters.Models.TechnologyFilter>
<div id="technologyFilters">
@for (int i = 0; i < Model.Count; i++)
{
<div id="technologyFilter">
@Html.HiddenFor(m => m[i].Name)
@Html.DisplayFor(m => m[i].Name)
</div>
}
</div>
The HTML data in both cases is differently generated and I would like to have a way to have it constant (to be like the first picture).
Without using Partial View:
Using Partial View:
Thanks for any help provided!
Upvotes: 1
Views: 159
Reputation: 56429
That's probably a good candidate for an EditorTemplate
to be honest, that way you don't have any issues with prefixing:
@Html.EditorFor(m => m.TechnologyFilters)
Without using an editor template though, a technique you can use is to specify the prefix in your partial declaration within the ViewDataDictionary
, by doing:
Html.RenderPartial("_TechnologyFilters", Model.TechnologyFilters, new ViewDataDictionary
{
TemplateInfo = new System.Web.Mvc.TemplateInfo { HtmlFieldPrefix = "TechnologyFilters" }
}))
Upvotes: 2