Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Controller parameter for a form element with a dot in it?

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.

like image 390
codeulike Avatar asked Oct 03 '10 19:10

codeulike


People also ask

What is ActionResult () in MVC?

An action result is what a controller action returns in response to a browser request. The ASP.NET MVC framework supports several types of action results including: ViewResult - Represents HTML and markup. EmptyResult - Represents no result.


2 Answers

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.

like image 192
Alexander Prokofyev Avatar answered Oct 25 '22 11:10

Alexander Prokofyev


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

like image 25
Clicktricity Avatar answered Oct 25 '22 11:10

Clicktricity