简体   繁体   English

绑定复杂对象模型以进行查看

[英]Bind complex object model to view

I need to bind a complex object(model) to the view. 我需要将一个复杂的对象(模型)绑定到视图。 I have a search model and search view.. 我有一个搜索模型和搜索视图。

Search Model, 搜索模型

public class SearchModel
{
    public SearchCriteria SearchCriteria { get; set; }
    .....
}

Search Criteria 搜索条件

public class SearchCriteria
{
    public int AccountId { get; set; }
    public string AccountName { get; set; }
    ......
}

Search 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)

This is rendered as 呈现为

<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="">

control name is rendering as SearchCriteria.AccountId , SearchCriteria.AccountName and control id is rendering as SearchCriteria_AccountId , SearchCriteria_AccountName 控件名称呈现为SearchCriteria.AccountIdSearchCriteria.AccountName ,控件ID呈现为SearchCriteria_AccountIdSearchCriteria_AccountName

and when submitting the form in get request, querystring will be looks like, 当在get请求中提交表单时,querystring会像这样,

?SearchCriteria.AccountId=1&SearchCriteria.AccountName=aaa

Is there any way to change them to display without SearchCriteria suffix? 有没有办法将它们更改为不带SearchCriteria后缀的显示?

so control name should render as AccountId , AccountName and control id should render as AccountId , AccountName 因此控件名称应呈现为AccountIdAccountName和控件ID应呈现为AccountIdAccountName

and querystring should looks like, 和querystring应该看起来像,

?AccountId=1&AccountName=aaa

There is no way to change that if you want MVC to do the automated binding. 如果您希望MVC执行自动绑定,则无法更改它。 You could of course provide your own name if you wanted. 如果需要,您当然可以提供自己的名字。 However, a more recommended approach would be to build a ViewModel like this: 但是,更推荐的方法是构建如下的ViewModel

public class SearchViewModel
{
    public int AccountId { get; set; }
    public string AccountName { get; set; }
    ...
}

that flattened the complex model. 使复杂的模型变得平坦。 The reason this is the recommended approach is because a View isn't really a complex model , it's simply a view of a more complex underlying model. 之所以建议使用这种方法,是因为View并不是真正的复杂模型 ,它只是更复杂的基础模型的视图 You could then use an auto mapper to very easily map the flattened ViewModel back into the complex model at the very top of your controller method. 然后,您可以使用自动映射器非常轻松地将展平的ViewModel映射回控制器方法顶部的复杂模型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM