Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update ModelState?

Tags:

c#

asp.net-mvc

This is a controller action that I call with ajax post 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, submit form doesn't have Username and Email fields, so they don't get passed by ajax call. When action gets called ModelStat.IsValid returns false, because these two properties are required. After I set valid values to properties, how do I trigger model validation to update ModelState?

like image 395
frennky Avatar asked Jan 31 '11 19:01

frennky


2 Answers

You can use a custom model binder to bind the comment's Username and Email properties from User.Identity. Because binding occurs before validation the ModelState will be valid then.

Another option is to implement a custom model validator for the Comment class, that checks the ControllerContext.Controller for a validated user.

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

like image 79
m0sa Avatar answered Nov 07 '22 20:11

m0sa


You can try calling the built in TryUpdateModel method which returns a boolean so you can check that value.

UPDATE: Try using TryUpdateModel with exceptions. Use a formcollection instead of Comment into the 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
        {
            //...
        }
    }
like image 42
Jon Avatar answered Nov 07 '22 21:11

Jon