开发者

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

开发者 https://www.devze.com 2023-01-18 19:02 出处:网络
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:

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 ob开发者_如何学JAVAject 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.


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.


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


As Clicktricity suggests in comments you may use

[HttpPost]
public ActionResult FooAction(FormCollection form)
{
    firstName = form["Contact.FirstName"];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号