这是我用ajax post方法调用的一个控制器操作:
[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
{
//...
}
}如果用户已登录,则提交表单没有用户名和电子邮件字段,因此ajax调用不会传递这些字段。当操作被调用时,ModelStat.IsValid返回false,因为这两个属性是必需的。在我为属性设置了有效值之后,我如何触发模型验证来更新ModelState?
发布于 2011-02-01 04:28:09
您可以使用自定义model binder从User.Identity绑定评论的用户名和电子邮件属性。因为绑定发生在验证之前,所以ModelState将在那时有效。
另一种选择是为Comment类实现一个自定义model validator,它检查ControllerContext.Controller中是否有经过验证的用户。
通过实现这些选项中的任何一个,您都可以删除第一个if check。
发布于 2011-02-01 04:15:24
您可以尝试调用内置的TryUpdateModel方法,该方法返回一个布尔值,以便您可以检查该值。
更新:尝试使用包含异常的TryUpdateModel。在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
{
//...
}
}https://stackoverflow.com/questions/4855259
复制相似问题