The Asp.net MVC 3 statement excludes some field validation in TryUpdateModel

I use ASP.NET MVC Razor And Data Annotation validators. My model:

public class Person { public int id { get; set; } [Required] public string FirstName { get; set; } [Required] public string LastName { get; set; } } 

FirstName And LastName - Requerd. I want to change FirstName. My method:

 public ActionResult Edit([Bind(Include = "FirstName")]Person person) { var p = GetPerson(); if (TryUpdateModel(p)) { //Save Changes; } } 

But TryUpdateModel always returns false. because LastName is not valid.

How to prevent LastName validation check in TryUpdateModel?

Note:

  • The code is simplified. my real code is very complicated.
  • I need to use Requierd for two properties
  • I do not want to use another model class
+7
source share
4 answers

I found Nice Solution. I have to remove an unused field from ModelState. then ModelState.IsValid returns true. first I need to create a new attribute class:

 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(); } } 

then I will add an attribute to my method:

 [ValidateOnlyIncomingValuesAttribute] public ActionResult Edit([Bind(Include = "FirstName")]Person person) { var p = GetPerson(); if (ModelState.IsValid) { TryUpdateModel(p); //Save Changes; } } 

Take a look at this: http://blog.stevensanderson.com/2010/02/19/partial-validation-in-aspnet-mvc-2/

+17
source

You can remove properties that you donโ€™t need before checking if the model is really

 ModelState.Remove("Email"); if (ModelState.IsValid) { // whatever you want to do } 
+13
source

A very simple solution that I found out.

 public ActionResult Edit(Person person) { ModelState.Remove("FirstName"); // This will remove the key var p = GetPerson(); if (TryUpdateModel(p)) { //Save Changes; } } } 
+7
source

Short answer: you cannot use default data annotations.

Longer answer: you have several options.

  • You can create your own validator annotations.
  • You can make your class class inherit from ivalidatableObject, and then implement the Validate method. (however, this is not a client-side check).
  • You can use a third-party validation library, such as FluentValidation.
  • You can create another model for this scenario.
  • You can remove the validation and simply add code to your action method, which validates the fields. (this is not recommended, as it increases the complexity of your controllerโ€™s actions, and you need to duplicate this functionality wherever you use this model).
+4
source

All Articles