开发者

Issue with ASP.NET MVC model binder

With this controller method: -

    [AcceptVerbs(HttpVerbs.Post)]
    public ViewResult Contact(Contact contactMessage)
    {
        return View();
    }

Why does this work...

public class Contact
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Message { get; set; }
}

<% using(Html.BeginForm()) { %>
<p>Name : <%= Html.TextBox("Name")%></p>
<p>Email : <%= Html.TextBox("Email")%></p>
<p>Message : <%= Html.TextBox("Message")%></p>
<p><input type=开发者_JAVA百科"submit" value="Send Data" /></p>

But this doesn't?

public class Contact
{
    public string ContactName { get; set; }
    public string ContactEmail { get; set; }
    public string ContactMessage { get; set; }
}

<p>Name : <%= Html.TextBox("ContactName")%></p>
<p>Email : <%= Html.TextBox("ContactEmail")%></p>
<p>Message : <%= Html.TextBox("ContactMessage")%></p>
<p><input type="submit" value="Send Data" /></p>

Please don't tell me that field names are only partially identified ?

Trust me - All I did was add the text "Contact" to each of the fields in the object and each of the fields in the form. Its almost as if MVC got confused with the fields all starting with the same first 7 characters.

What gives ?

Can anyone shed any light on this ?

Paul.


I currently can't find any reasonable explanation as to why the second is not working. But it works if you change your action signature to look like this:

public ViewResult Index([Bind(Prefix="")]Contact contactMessage)

I suppose this has something to do with the DefaultModelBinder.


UPDATE: Ok, this starts to be really funny:

// Not working
public ViewResult Index(Contact contactMessage)

// Not working
public ViewResult Index(Contact contactmessage)

// Working
public ViewResult Index(Contact contact)

// Working
public ViewResult Index(Contact contactMsg)

// Working
public ViewResult Index(Contact abc)

Strange indeed!


UPDATE2:

Ok got it. You have a property called ContactMessage in your model and the variable name passed in the action is also called contactMessage. This is where the ambiguity comes from. No bug in the DefaultModelBinder. He can't bind at the same time to a property of type string and Contact, case closed :-)


Is it possible the view auto-recompiled when you refreshed your browser, but the overall project hasn't been Rebuilt since you changed the property names?


Code your Textboxes like this:

 <%=html.TextBox("Contact.Name")%>

and you Action signature like this:

public ViewResult Index([Bind(Prefix="Contact")]Contact contactMessage)

I hope this helps and good luck


<% using(Html.BeginForm()) { %> 

is missing from your non-working example.

Or.. Maybe contactMessage parameter name is conflicting with the variable number in the form post.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜