我正在使用ASP.NET MVC Razor和Data Annotation验证器
我的模特:
我的模特:
public class Person { public int id { get; set; } [required] public string FirstName { get; set; } [required] public string LastName { get; set; } }
FirstName和LastName是Requerd.
我想编辑FirstName.我的Methode是:
public ActionResult Edit([Bind(Include = "FirstName")]Person person) { var p = GetPerson(); if (TryUpdateModel(p)) { //Save Changes; } }
但是TryUpdateModel总是返回false.因为LastName无效.
如何防止在TryUpdateModel中检查LastName的检查?
注意:
>代码是简化的.我真正的代码很复杂
>我必须使用Requierd for Two Property
>我不想使用不同的模型类
解决方法
我找到了Nice Solution.我必须从ModelState中删除未使用的Field.然后ModelState.IsValid返回true.首先我需要Create New Attribute类:
public class ValidateOnlyIncomingValuesAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { var modelState = filterContext.Controller.ViewData.ModelState; var valueProvider = filterContext.Controller.ValueProvider; var keysWithNoIncomingValue = modelState.Keys.Where( x=>!valueProvider.ContainsPrefix(x) ); foreach (var key in keysWithNoIncomingValue) modelState[key].Errors.Clear(); } }
[ValidateOnlyIncomingValuesAttribute] public ActionResult Edit([Bind(Include = "FirstName")]Person person) { var p = GetPerson(); if (ModelState.IsValid) { TryUpdateModel(p); //Save Changes; } }
看看这个:http://blog.stevensanderson.com/2010/02/19/partial-validation-in-aspnet-mvc-2/