views:

54

answers:

3

If you're using the Html.TextBoxFor() type methods, you may well end up with Form controls that have dots in their names, like this:

<input type="text" name="Contact.FirstName" id="Contact_FirstName" />

If you want MVC to map those named fields to parameters in your controller (as opposed to an object parameter or whatever), you have to get the parameter names right. What to do about the dots?

Neither this:

[HttpPost]
public ActionResult FooAction(string firstName)

not this:

[HttpPost]
public ActionResult FooAction(string contact_FirstName)

seem to work.

Edit: Having a suitable object parameter would work (eg see clicktricity's answer), but I'm looking for a way to do it with named value parameters.

+3  A: 

Depending on the other form controls, you should be able to have the MVC default model binder construct a Contact object for you. Then the signature of your action method would be:

[HttpPost]
public ActionResult FooAction(Contact contact)

Then the Contact.FirstName (and any other fileds) will be bound correctly

Clicktricity
Thanks, yes, that would work but I'm interested if the string parameter method can also work.
codeulike
Unfortunately not. This is one of the problems with "convention over configuration" when you don't want to follow the convention. If you need to bind to the individual value, either write a custom model binder, or fetch the value from the Forms collection
Clicktricity
Ah, ok. So its not possible with string parameters. Thanks
codeulike
Turns out there is a way to do it, with BindAttribute, see Alex P's answer.
codeulike
+1  A: 

As Clicktricity suggests in comments you may use

[HttpPost]
public ActionResult FooAction(FormCollection form)
{
    firstName = form["Contact.FirstName"];
}
Alexander Prokofyev
+2  A: 

I have found another way, a kind of hack because I believe this is misuse of BindAttribute, to associate firstName parameter with Contact.FirstName input element:

[HttpPost]
public ActionResult FooAction([Bind(Prefix="Contact.FirstName")]string firstName)

This for sure works with ASP.NET MVC 1.

Alexander Prokofyev
Hey, thats interesting. Why do you call it a misuse? Isn't this what BindAttribute is for?
codeulike
It seems BindAttribute.Prefix property was intended only to give an alias to instance of complex type.
Alexander Prokofyev
It works on MVC 2 too. I'd call this 'creative' rather than a hack.
codeulike