Binding Entity Framework Collections Simply Using ASP.NET MVC
- by jpcmorton
To begin with: Using Entity Framework v4.0. ASP.NET MVC 2.0. Visual Studio 2010.
I have a model that consists simply of an order & order items. What I want to do is simply bind that model without too much hassle where possible (avoiding type converters, etc).
Simply the model looks like this:
public class Order {
public int ID { get; set; }
public string OrderNumber { get; set; }
public EntityCollection<OrderItem> Items { get; set; }
}
public class OrderItem {
public int ID { get; set; }
public string Qty { get; set; }
}
This is as simple as I want to keep it. This model is coming directly from the code generated by the entity framework generator. I would prefer to use the model directly from the entity framework (I know there are views saying this is a bad thing, but alas). I then have the View looking like this:
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.ID) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.ID) %>
<%: Html.ValidationMessageFor(model => model.ID) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.OrderNumber) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.OrderNumber)%>
<%: Html.ValidationMessageFor(model => model.OrderNumber)%>
</div>
<div id="lineItems">
Where I need to put my line items to be edited, inserted
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
What I want to do is have a situation where I can use dynamic line items (using javascript).
Problems are this:
How to go about inserting the initial line item (within the lineItems div). This need to be strongly typed and use the built in validation framework of MVC.
Best way to go about inserting line items dynamically so that on the postback there is a complete bind to the model without too much messing around (id = 1,2,3,4, etc).
Any help, examples, tips, etc would be appreciated.