开发者

ASP.MVC ModelBinding Behaviour

开发者 https://www.devze.com 2022-12-18 18:52 出处:网络
This one has me s开发者_开发百科tumped, despite the numerous posts on here. The scenario is a basic MVC(2) web application with simple CRUD operations. Whenever the edit form is submitted and the Upd

This one has me s开发者_开发百科tumped, despite the numerous posts on here.

The scenario is a basic MVC(2) web application with simple CRUD operations. Whenever the edit form is submitted and the UpdateModel() called, an exception is thrown:

System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException was unhandled by user code

This occurs against a DropDownList value which is a foreign key on the entity table. However, there is another DropDownList list on the form, representing another foreign key, which does not throw the error (unsurprisingly). Changing the property values manually inside the Edit Action:

Recipe recipe = repository.GetRecipe(int.Parse(formValues["recipeid"]));
recipe.CategoryId = Convert.ToInt32(formValues["CategoryId"].ToString());
recipe.Page = int.Parse(formValues["Page"].ToString());
recipe.PublicationId=Convert.ToInt32(formValues["PublicationId"].ToString());

Allows the CategoryId and Page properties to be updated, and then the error is thrown on the PublicationId. All of the referential integrity is checked an the same in the db and the dbml.

Any light shed on this would be most welcome.


This error has nothing whatsoever to do with model binding. Rather, it's strictly related to LINQ to SQL. You can find a reasonable explanation of what causes it in this post.


Change your code with below

instead of

recipe.CategoryId = Convert.ToInt32(formValues["CategoryId"].ToString());

write this

recipe.Category = db.GetCatById(formValues["CategoryID"]);
0

精彩评论

暂无评论...
验证码 换一张
取 消