How do I specify a strongly-typed html helper that uses a nested class of the model instead of the model itself?
I am creating a strongly-typed search form in ASP.NET MVC 2 that posts to a results page via FormMethod.Get (i.e. the form inputs and their values are posted to the search results query string). How do I specify strongly-typed html helpers that use a nested class of the model instead of the model itself so that I don't get the dot notation for the input names in the query string?
My strongly-typed view model class looks like:
public class SearchViewModel
{
public SearchQuery SearchQuery { get; set; }
public IEnumerable<SelectListItem> StateOptions { get; set; }
...
}
The SearchQuery class looks like:
public class SearchQuery
{
public string Name { get; set; }
public string State { get; set; }
...
}
Doing this:
<%= Html.TextBoxFor(m => m.SearchQuery.Name)%>
will generated an input with name SearchQuery.Name
, which will place &SearchQuery.Name=blah
in the query st开发者_如何学JAVAring when the form is posted. Instead, I would prefer just &Name=blah
, as only SearchQuery properties will have associated form elements.
I'm assuming I have to do something with the Html.TextBoxFor
Linq expression, but I can't seem to get the syntax right..
Thanks for your help!!
One way around this is to make Name a propery of the ViewModel ie:
public string Name{
get{
return this.SearchQuery.Name;
}
}
And in the view:
<%= Html.TextBoxFor(m => m.Name)%>
Whether or not this is a good idea is another question.
精彩评论