ASP.Net MVC 3 - Bind Include/Exclude and validation
Although I use Bind-Include to edit only a portion of an object properties, validation for pro开发者_C百科perties that are not include is still firing, an my model state is invalid after a form submission.
Here is a simplified version of my model:
public partial class MyObject
{
public int MyObjectId { get; set; }
public int personId { get; set; }
public string myString1 { get; set; }
public Nullable<int> friend1Id { get; set; }
public Nullable<int> friend2Id { get; set; }
public virtual People person { get; set; }
public virtual People Friend1 { get; set; }
public virtual People Friend2 { get; set; }
}
And I have a controller to edit only the friends (Friend1 and Friend2) on that object that looks like this:
[HttpPost]
public ActionResult Assignation([Bind(Include = "friend1Id,friend2Id")]MyObject myObject)
{
if (ModelState.IsValid)
{
db.Entry(myObject).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.friend1Id = new SelectList(db.People, "personId", "Name", myObject.friend1Id);
ViewBag.friend2Id = new SelectList(db.Divisions, "personId", "Name", myObject.friend2Id);
return View(myObject);
}
On my view I simply have 2 dropdown lists to select friends, and a Save button. When I click on save however, my model comes back as invalid. If I look a the collections of properties inside ModelState, I find an error message stating that myString1 is required. myString1 is of type nvarchar(100) NOT NULL in the database, but I would have thought that there would be no validation for that field since I did not include it in my binding. Is my understanding of Bind wrong? Please bear with me, I am new to ASP.Net MVC. I am using MVC 3 and EF 4.1 and strongly typed views.
I think the validation still assumes that you want to work with a valid model. Even though you just bind 2 properties now, the default values of the other properties could still ensure a valid model. If you want to work with this partly invalid model and ignore the other fields you can also check specifically for those 2 properties, if you use the IsValidField method where you can pass the name of the property:
ModelState.IsValidField("friend1Id") && ModelState.IsValidField("friend2Id")
What I don't fully understand is why you get such a validation error if you have no required attribute on that property. Or is it just truncated in your question?
Alternatively, you could have a model class for this scenario that has just those 2 fields. It would probably better describe the situation, and also the update of the database entry would be more clear (looking up an existing entity by id (btw where is the id coming from currently?), and setting the properties of the persistent entity with the model properties coming with the post. I still wonder whether the code in the "if valid" branch would really save something as you expect it...)
精彩评论