C# – How to update ModelState

asp.net-mvcc

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?

Best Answer

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.