views:

57

answers:

1

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 string 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!!

A: 

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.

James Connell
Not sure I follow- what I just showed you is functionally equivalent to what you are already doing, MVC will just not add the SearchQuery prefix. That is, in the view, m.Name and m.SearchQuery.Name are the same, the first one is just a 'shortcut' to the second.
James Connell
Sorry, I didn't look closely enough at your answer. The problem is that I have to create a duplicate set of properties on the view model that mirror the SearchQuery properties. It would be preferable if I could avoid having to do that..
note.. I deleted my first comment because it was not relevant.
You are right, its a duplication of the child object which is annoying. The only other alternative I know of is to use the bind prefix syntax on the controller (ie public void SomeAction([Bind(Prefix=SearchQuery")]SearchQuery q){ ... })
James Connell
The bind prefix attribute is pretty neat! That's not really my issue either, though - I discovered that for the action method definition, I can also name the search query the same name as the view model's property name, e.g. public ActionResult SearchResults(SearchQuery searchQuery) to have MVC auto-bind the query string values to the SeachQuery object.

related questions