ASP.NET MVC 4 Model binding null on post(controller方法参数绑定时始终为null)

http://ideasof.andersaberg.com/development/aspnet-mvc-4-model-binding-null-on-post

这里介绍的这种情况是比较操蛋的一种情况:

即、如果controller中方法参数名称,和要绑定的模型的属性同名时,就会出现对应参数始终是null的情况;

详细参见下面:

So you have your form in MVC 4 and you want to post it to a Action on a controller.

The form represents a class, let’s pretend this is a contact form and you have a a class that look like this:

class ContactMessage
 {
    public string Name { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }
    public string Message { get; set; }
}

And your action, looks like this:

    [HttpPost]
    public ActionResult Kontakt( ContactModel message)
    {
        var mailer = new ContactMailer();
        var msg = mailer.ContactMessage(message);
        msg.Send();
   }

注意:上面标注红色背景色的文字,他们名字重复了,会导致绑定失败。

Well, that should work, right? Right? RIGHT? Well - No.

Because, the Model Biner in .NET MVC 4 will doubt what you mean. Because - the post value looks like this:

 Name=Anders&Phone=123&Email=abc&***Message***=Hello!

You see that Message property name? That will fuck up the ModelBiner. Because… in your Action, you are waiting for the incoming property Message (it will use the name of variable). But what you really want is the full, complex, model and just calling it Message.

The solution

Do not name your incoming variables in the Action the same as you do in the model being posted. That will mess up the Model Binder.

Change your action to this:

    [HttpPost]
    public ActionResult Kontakt( ContactModel INCOMINGmessage)
    {
        var mailer = new ContactMailer();
        var msg = mailer.ContactMessage(INCOMINGmessage);
        msg.Send();
   }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值