我需要将一个复杂的对象(模型)绑定(bind)到 View 。我有一个搜索模型和搜索 View ..
搜索模型,
public class SearchModel
{
public SearchCriteria SearchCriteria { get; set; }
.....
}
搜索条件
public class SearchCriteria
{
public int AccountId { get; set; }
public string AccountName { get; set; }
......
}
搜索 View
@Html.LabelFor(x => x.SearchCriteria.AccountId, "Account ID")
@Html.TextBoxFor(x => x.SearchCriteria.AccountId)
@Html.LabelFor(x => x.SearchCriteria.AccountName, "Account Name")
@Html.TextBoxFor(x => x.SearchCriteria.AccountName)
这呈现为
<label for="SearchCriteria_AccountId">Account ID</label>
<input id="SearchCriteria_AccountId" name="SearchCriteria.AccountId" type="text" value="">
<label for="SearchCriteria_AccountName">Account Name</label>
<input id="SearchCriteria_AccountName" name="SearchCriteria.AccountName" type="text" value="">
控件名称呈现为 SearchCriteria.AccountId
、SearchCriteria.AccountName
,控件 ID 呈现为 SearchCriteria_AccountId
、SearchCriteria_AccountName
并且在get请求中提交表单时, 查询字符串看起来像,
?SearchCriteria.AccountId=1&SearchCriteria.AccountName=aaa
有什么方法可以将它们更改为在没有 SearchCriteria
后缀的情况下显示?
所以
控件名称应呈现为 AccountId
、AccountName
,控件 ID 应呈现为 AccountId
、AccountName
查询字符串应该是这样的,
?AccountId=1&AccountName=aaa
最佳答案
如果您希望 MVC 执行自动绑定(bind),则无法更改它。如果需要,您当然可以提供自己的名字。但是,更推荐的方法是构建一个 ViewModel
,如下所示:
public class SearchViewModel
{
public int AccountId { get; set; }
public string AccountName { get; set; }
...
}
将复杂模型展平。这是推荐方法的原因是因为 View
实际上不是一个复杂模型,它只是一个更复杂的底层模型的 View .然后你可以使用 auto mapper非常容易地将扁平化的 ViewModel
映射回 Controller 方法最顶部的复杂模型。
关于c# - 将复杂对象模型绑定(bind)到 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16941208/