I am using 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 are Requerd. I want to Edit FirstName. My Methode is:
public ActionResult Edit([Bind(Include = "FirstName")]Person person)
{
var p = GetPerson();
if (TryUpdateModel(p))
{
//Save Changes;
}
}
But TryUpdateModel always return false. because LastName is Invalid.
How Can I Prevent check Validation Of LastName in TryUpdateModel?
Note:
I found Nice Solution. I must remove unused Field from ModelState. then ModelState.IsValid return true. first I need Create 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 Add Attribute on my methode:
[ValidateOnlyIncomingValuesAttribute]
public ActionResult Edit([Bind(Include = "FirstName")]Person person)
{
var p = GetPerson();
if (ModelState.IsValid)
{
TryUpdateModel(p);
//Save Changes;
}
}
Look at this: http://blog.stevensanderson.com/2010/02/19/partial-validation-in-aspnet-mvc-2/
You can remove the properties you don´t need before checking if the model is valid
ModelState.Remove("Email");
if (ModelState.IsValid)
{
// whatever you want to do
}
A very simple solution that I figured out.
public ActionResult Edit(Person person)
{
ModelState.Remove("FirstName"); // This will remove the key
var p = GetPerson();
if (TryUpdateModel(p))
{
//Save Changes;
}
}
}
Short Answer: You can't, not using the default Data Annotations.
Longer Answer: You have several options.
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