我有一个以下 View 模型,它将由我正在处理的搜索控件使用。
public class SearchViewModel
{
public SearchViewModel()
{
SearchLocation = new SearchLocationViewModel();
SearchCategories = new SearchCategoriesViewModel();
}
public SearchLocationViewModel SearchLocation { get; set; }
public SearchCategoriesViewModel SearchCategories { get; set; }
}
现在,SearchCategoriesViewModel 具有以下结构:
public class SearchCategoriesViewModel
{
[Display(Name = "Categories")]
public IList<SearchCategoryViewModel> Categories { get; set; }
public SearchCategoriesViewModel()
{
Categories = new List<SearchCategoryViewModel>();
}
}
最后,搜索类别 View 模型具有以下结构:
public class SearchCategoryViewModel
{
[Required]
[Display(Name="Id")]
public int Id { get; set; }
[Display(Name="Name")]
public String Name { get; set; }
public bool IsSelected { get; set; }
}
当我提交搜索请求时,SearchLocationViewModel 带有提交的参数,但是 SearchCategoriesViewModel 来自空(非空)。
下面是我的 SearchCategoryViewModel 的编辑器模板:
@model MyDLL.WebUI.Models.SearchCategoriesViewModel
@foreach (var c in Model.Categories)
{
@Html.Label(c.Name);
@Html.CheckBox(c.Name,c.IsSelected);
}
我使用以下 View 来生成搜索控件:
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<div id="search">
@Html.EditorFor(m => m.SearchCategories, "SearchCategory")
@Html.EditorFor(m => m.SearchLocation, "SearchLocation")
</div>
<p>
<input type="submit" value="Create" />
</p>
}
我最终得到以下标记:
<h2>Search</h2>
<form action="/Settings/Search" method="post">
<label for="SearchCategories_Professional">Professional</label>
<input id="SearchCategories_Professional" name="SearchCategories.Professional" type="checkbox" value="true" />
<input name="SearchCategories.Professional" type="hidden" value="false" />
<label for="SearchCategories_Associate">Associate</label><input id="SearchCategories_Associate" name="SearchCategories.Associate" type="checkbox" value="true" />
<input name="SearchCategories.Associate" type="hidden" value="false" />
<p>
<input type="submit" value="Create" />
</p>
</form>
我怀疑参数没有通过,因为生成的标记是错误的。你们中有人尝试过从复杂对象生成部分 View 吗?我不想传递 IEnumerable,我宁愿将它封装在一个单独的类中,以便将来在需要时扩展/删除它。
谢谢
最佳答案
因为您有一个静态列表,所以您可以快速破解创建正确绑定(bind)的标记的方法:
@model MyDLL.WebUI.Models.SearchCategoriesViewModel
@{
var i = 0;
}
@foreach (var c in Model.Categories)
{
@Html.Hidden("Categories[" + i.ToString() + "].Id", c.Id);
@Html.Hidden("Categories[" + i.ToString() + "].Name", c.Name);
@Html.Label(c.Name);
@Html.CheckBox("Categories[" + i.ToString() + "].IsSelected",c.IsSelected);
}
这是一个快速而丑陋的解决方案。但是,我建议您重新考虑如何在局部 View 中生成标记。
关于asp.net-mvc - MVC 3 - 使用 List 类型属性绑定(bind)到复杂类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7176702/