Note that there are some explanatory texts on larger screens.

plurals
  1. POASP.NET MVC 2 RC model binding with NHibernate and dropdown lists
    primarykey
    data
    text
    <p>I have problem with model binding in my ASP.NET MVC 2 RC application that uses NHibernate for data access. We are trying to build the application in a Ruby on Rails way and have a very simple architecture where the domain entities are used all the way from the database to the view.</p> <p>The application has a couple of domain entities which can be illustrated by the following two classes:</p> <pre><code>public class Product { ... public Category Category { get; set; } } public class Category { public int Id { get; set; } public string Name { get; set; } } </code></pre> <p>In the view that renders the edit form has the following statement to display a dropdown list:</p> <pre><code>&lt;%= Html.DropDownListFor(model =&gt; model.Category.Id, new SelectList(ViewData["categories"] as IList&lt;Category&gt;, "Id", "Name"), "-- Select Category --" ) %&gt; </code></pre> <p>Please disregard the use of "non-typed" view data to hold the category collection. </p> <p>The action method that receives the form post is similar to to the following. Note that the TransactionFilter attribute adds NHibernate transaction handling and commits the transaction if no exceptions occur and validation succeeds.</p> <pre><code>[HttpPost] [TransactionFilter] public ActionResult Edit(int id, FormCollection collection) { var product = _repository.Load(id); // Update the product except the Id UpdateModel(product, null, null, new[] {"Id"}, collection); if (ModelState.IsValid) { return RedirectToAction("Details", new {id}); } return View(product); } </code></pre> <p>My issue is that the product.Category.Id is set with the value selected in the form, e.g. Category.Id = "2". Using the default model binder results in the following type of NHibernate exception: </p> <pre><code>identifier of an instance of Name.Space.Entities.Category was altered from 4 to 2 </code></pre> <p>That makes a lot of sense since the product already has a category assigned and only the primary key of that existing category is being changed. Another category instance should have been assigned instead. </p> <p>I guess a custom ModelBinder can be created to handle this issue but is there a simpler way to make this work? Can (and should) the domain entities be modified to handle this?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload