Wednesday, 15 September 2010

asp.net mvc - Client or server validation doesn't work with Data Annotations -



asp.net mvc - Client or server validation doesn't work with Data Annotations -

i'm developing mvc 4 application entity framework 6 , encountered problem info annotations. no matter annotation use, isn't validate. i'm using next view model render form:

public class userviewmodel { [required(errormessage = "first name required")] [display(name = "first name")] [stringlength(100, minimumlength = 2)] public string firstname { get; set; } ... }

in view:

@html.labelfor(m => m.firstname) @html.editorfor(m => m.firstname) @html.validationmessagefor(m => m.firstname)

and gets rendered:

<label for="firstname">first name</label> <input class="text-box single-line" id="firstname" name="firstname" type="text" value="" /> <span class="field-validation-valid" data-valmsg-for="firstname" data-valmsg-replace="true"></span>

when click submit button client validation doesn't triggered , in controller modelstate.isvalid true.

update:

controller:

[httpget] public actionresult edit(int? id) { var model = _userservice.getuserbyid(id); homecoming view(model); } [httppost] public actionresult edit(userviewmodel model) { if (modelstate.isvalid == true) { _userservice.save(model); homecoming view(model); } homecoming view(model); }

the problem post controller, map user object, not userviewmodel. 1 of reasons server-side validation not triggered.

as client-side validation, i'm not sure, same error - view based on user type, rather on userviewmodel.

so controller should this:

[httpget] public actionresult edit(int? id) { var model = _userservice.getuserbyid(id); var viewmodel = new userviewmodel() { firstname = model.firstname, lastname = model.lastname, // other properties }; homecoming view(viewmodel); } [httppost] public actionresult edit(userviewmodel viewmodel) { if (modelstate.isvalid == true) { var model = new user() { firstname = viewmodel.firstname, lastname = viewmodel.lastname, // other properties }; _userservice.save(model); homecoming view(model); } homecoming view(model); }

and top of edit.cshtml should have @model userviewmodel.

hope helps

asp.net-mvc validation

No comments:

Post a Comment