How to update ModelState?

This is a controller action that I invoke using the post ajax method:

[HttpPost] public ActionResult Add(Comment comment) { if (User.Identity.IsAuthenticated) { comment.Username = User.Identity.Name; comment.Email = Membership.GetUser().Email; } if (ModelState.IsValid) { this.db.Add(comment); return PartialView("Comment", comment); } else { //... } } 

If the user is logged in, there are no user name and email fields in the send form, so they are not transmitted when ajax is called. When the action is called ModelStat.IsValid returns false because these two properties are necessary. After I set valid values ​​for the properties, how do I initiate a model check to update the ModelState?

+8
c # asp.net-mvc
source share
2 answers

You can use custom model binding to associate the Username and Email Properties comments from User.Identity. Since binding occurs before validation, ModelState will be valid.

Another option is to implement a custom model validator for the Comment class, which checks the ControllerContext.Controller for the user being verified.

By implementing any of these options, you can remove the first if you check.

+4
source share

You can try creating a built-in TryUpdateModel method that returns a boolean value so that you can check this value.

UPDATE. Try using TryUpdateModel with exceptions. Use an ActionCollection instead of a comment in an Action.

 [HttpPost] public ActionResult Add(FormCollection collection) { string[] excludedProperties = new string[] { "Username". "Email" }; var comment = new Comment(); if (User.Identity.IsAuthenticated) { comment.Username = User.Identity.Name; comment.Email = Membership.GetUser().Email; } TryUpdateModel<Comment>(comment, "", null, excludedProperties, collection.ToValueProvider()); if (ModelState.IsValid) { this.db.Add(comment); return PartialView("Comment", comment); } else { //... } } 
+3
source share

All Articles