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?
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.
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
{
//...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With