Validation does not work with ViewModel

Ok, I have a ViewModel that looks like this:

public class UserLogin
{
    [Required]
    public string EmailAddress { get; set; }

    [Required]
    public string Password { get; set; }
}

My controller is as follows:

[HttpPost]
public ActionResult LogIn(UserLogin model)
{
    if (!ModelState.IsValid)
    {
        // ...
    }
}

My view is as follows:

<% Html.BeginForm("Join", "User", FormMethod.Post); %>
    <%= Html.Hidden("ReturnUrl", Request.Url.AbsolutePath) %>

    <%= Html.TextBoxFor(c => c.EmailAddress, new { id = "join-emailaddress", @class = "text", uiHintText = "Email address" })%>
    <%= Html.ValidationMessageFor(c => c.EmailAddress, "*") %>

    <%= Html.PasswordFor(c => c.Password, new { id = "join-password", @class = "text", uiHintText = "Password" })%>
    <%= Html.ValidationMessageFor(c => c.Password, "*")%>

    <%= Html.PasswordFor(c => c.PasswordConfirm, new { id = "join-password-confirm", @class = "text", uiHintText = "Password (repeat)" })%>
    <%= Html.ValidationMessageFor(c => c.PasswordConfirm, "*")%>

    <input type="submit" value="Sign me up!" class="submit" />
<% Html.EndForm(); %>                

If I submit the form without entering any of the fields, I sequentially get the value "true" for "ModelState.IsValid".

Should it be "false" since I marked these fields as "Required" and did not enter any values?

+3
source share
3 answers

Take a look at the latest RC for ASP.NET MVC. It contains some fixes for this.

http://haacked.com/archive/2010/02/04/aspnetmvc2-rc2.aspx

In particular, from the release notes:


ASP.NET MVC 1.0 ASP.NET MVC 2 RC 2 , . ASP.NET MVC 2 RC2 , , , .

. :

ASP.NET MVC
http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html

+2

, ASP.NET MVC1. , Global.asax.vb.

Sub Application_Start()
    RegisterRoutes(RouteTable.Routes)

    'Added following line
    ModelBinders.Binders.DefaultBinder = New Microsoft.Web.Mvc.DataAnnotations.DataAnnotationsModelBinder()        
End Sub

Microsoft.Web.Mvc.DataAnnotations.dll. http://aspnet.codeplex.com/releases/view/24471

+1

.

[] ViewModel .

:

[Required(ErrorMessageResourceName = "FirstNameError", 
          ErrorMessageResourceType = typeof(MyResourceFile))]
public string FirstName { get; set; }

FirstNameError ""; - "" , , .

, , , ModelState.IsValid .

, , , .

(Yes, I should have mentioned from the very beginning that I use resources. I mistakenly thought that it did not matter, but it turned out that it was very important.)

+1
source

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


All Articles