Reputation: 19606
I have a view tied to a strongly typed ViewModel but I'm not using the MVC3 HTML helpers, just normal HTML input
tags. However, this seems to not be passing the values correctly to the action method as the ViewModel is entirely null.
ViewModel:
class QuoteSearch {
public long? CustomerId { get; set; }
public string CustomerFirstName { get; set; }
public string CustomerLastName { get; set; }
}
View:
@model QuoteSearch
<form action="/quotes/search" method="POST">
<p>Customer ID: <input id="CustomerIdField" name="CustomerId" type="text" /></p>
<p>Customer First Name: <input id="CustomerFirstNameField" name="CustomerFirstName" type="text"/></p>
<p>Customer Last Name: <input id="CustomerLastNameField" name="CustomerLastName" type="text"/></p>
<p><button id="SearchButton" type="submit">Search</button></p>
</form>
Controller:
[HttpPost]
public ActionResult Search(QuoteSearch search) {
// checking if fields are set here.
}
I seem to remember there being a way to NOT have to use the Html helpers but still use a strongly-typed model (as opposed to a FormCollection
); I thought it involved setting the name attribute to be the exact name of the property on the model, but I seem to have been mistaken.
Upvotes: 2
Views: 1134
Reputation: 2475
Try name="[ViewModel].[FieldName]" and id="[ViewModel]_[FieldName]"
These are what values I have in the input tags when using the HTML helpers.
So for you it would be:
<input type="text" name="QuoteSearch.CustomerId" id="QuoteSearch_CustomerId" />
etc..
Upvotes: 0
Reputation: 3326
Your names don't all align (as suggested in the comments) but for the fields that do line up, the model is correctly populated when I execute the above code (names are there, CustomerId is null).
Are you setting a breakpoint, and do you know that the code is being hit?
Please also confirm that your controller is called Quotes. Even if it is, you will be better to use:
<form action="@Url.Action("search", "quotes")" method="POST">
...so that routing works even if you add areas etc. The Url helper will work out the correct path for the request based on your routing rules.
Finally, if you're not hitting that execution point with a breakpoint set, be sure to use F12/dev tools to monitor your network requests and make sure that the correct address is being called. The above snippet should also help resolve that.
Hope that helps some.
Upvotes: 1