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
and when submitting the form in get request, querystring will be looks like,
?SearchCriteria.AccountId=1&SearchCriteria.AccountName=aaa
Is there any way to change them to display without SearchCriteria
suffix?
so control name should render as AccountId
, AccountName
and control id should render as AccountId
, AccountName
and querystring should looks like,
?AccountId=1&AccountName=aaa
There is no way to change that if you want MVC to do the automated binding. You could of course provide your own name if you wanted. However, a more recommended approach would be to build a ViewModel
like this:
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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.