Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update one to many relationship entity from same view?

Table Product Product Id Product Name

Table Supplier SupplierId ProductId SupplierName

When I create a New Product, I want to have a textbox to enter a supplier as well on the same view. Is this a good practice? Since Product can have many Suppliers, I want to be able to add more Supplier records from the same view. How do I do that?

I am trying to figure out what do I put in the aspx page?

If I put something like <%= Html.TextBoxFor(model => model.Supplier) %> I see a textbox with System.Data.Objects.DataClasses.EntityCollection`1[MyProject.Mvc.Models.Supplier] in it.

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"  
Inherits="System.Web.Mvc.ViewPage<MyProject.Mvc.Models.ProductFormViewModel>" %>
<%= Html.ValidationSummary("Please correct the errors and try again.") %>
<% using (Html.BeginForm()) {%>
<fieldset>
<legend>Fields</legend>

<div class="editor-label">
    <%= Html.LabelFor(model => model.Product.ProductId) %>
</div>
<div class="editor-field">
    <%= Html.TextBoxFor(model => model.Product.ProductId) %>
    <%= Html.ValidationMessageFor(model => model.Product.ProductId) %>
</div>

<div class="editor-label">
    <%= Html.LabelFor(model => model.Product.ProductName) %>
</div>
<div class="editor-field">
    <%= Html.TextBoxFor(model => model.Product.ProductName) %>
    <%= Html.ValidationMessageFor(model => model.Product.ProductName) %>
</div>

<div class="editor-label">
    <%= Html.LabelFor(model => model.Product.Description) %>
</div>
<div class="editor-field">
    <%= Html.TextBoxFor(model => model.Product.Description) %>
    <%= Html.ValidationMessageFor(model => model.Product.Description) %>
</div>            
<p>
    <input type="submit" value="Create" />
</p>
</fieldset>

<% } %>

ProductViewModel

public class ProductFormViewModel
{
    public Product Product{ get; private set; }
    public IEnumerable<Supplier> Supplier { get; private set; }

    public ProductFormViewModel()
    {
        Product = new Product();
    }

    public ProductFormViewModel(Product product)
    {
        Product = product;
        Supplier = product.Supplier;
    }
}
like image 217
Picflight Avatar asked Nov 15 '22 12:11

Picflight


1 Answers

I think you will find Steven Sanderson's blogpost about editing variable length lists in ASP.NET MVC 2 really useful. He also has another blogpost about validating such a list.

like image 87
Kristof Claes Avatar answered Dec 11 '22 02:12

Kristof Claes