Problem with binding to ASP.NET MVC model

Using this controller method: -

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

Why does it 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="submit" value="Send Data" /></p>

But is that not so?

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 do not tell me that field names are only partially identified?

Believe me. All I did was add the text “Contact” to each of the fields of the object and each of the fields in the form. Its almost as if MVC got confused with fields starting from the very first 7 characters.

What gives?

Can anyone shed some light on this?

Pavel.

+3
source share
4 answers

Currently, I cannot find a reasonable explanation of why the second does not work. But it works if you change your action signature to look like this:

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

I believe this has something to do with DefaultModelBinder.


UPDATE: , :

// 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)

!


UPDATE2:

. , ContactMessage , , , ContactMessage. . DefaultModelBinder. string Contact, case closed: -)

+4

, , , ?

+2

:

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

Action :

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

, .

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

.

.. , contactMessage .

0

Source: https://habr.com/ru/post/1721372/


All Articles