views:

135

answers:

1

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;
    }
}
+1  A: 

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.

Kristof Claes