开发者

MVC2 How To Edit Multiple Linked Customer Addresses

开发者 https://www.devze.com 2023-01-31 16:40 出处:网络
A Customer has a billing and delivery address, so given the following database schema Customer(CustomerId)

A Customer has a billing and delivery address, so given the following database schema

  • Customer(CustomerId)
  • Address(AddressId)
  • CustomerAddresses(CustomerId,AddressId)

And the following Enitity Framework class

public class Customer
{
    public IEnumerable<Address> Addresses { get; set; }
}

I output my input boxes in my view like so

<% foreach (var address in Model.Addresses) { %> 

    <%: Html.TextBoxFor(model => address.Address1) %>

<% } %>

When I post the form values after entering DeliveryAddress1 and BillingAddress1 and then iterate over the FormCollection keys I get the following value

Customer.address.Address1 = "Delivery开发者_JS百科Address1,BillingAddress1"

The question is how do I distinguish between the two records?


I would recommend you using editor templates. This way you don't need to write ugly loops in your views and the helpers will take care of generating proper names for the input fields.

So in your main view instead of writing all the code you've shown simply:

<%: Html.EditorFor(x => x.Addresses) %>

And then create an editor template for an address (~/Views/Home/EditorTemplates/Address.ascx)

<%@ Control 
    Language="C#" 
    Inherits="System.Web.Mvc.ViewUserControl<YourApp.Models.Address>" %>    
<%: Html.TextBoxFor(x => x.Address1) %>

Notice the name and location of the editor template. The location should be in the EditorTemplates folder (it could also be in ~/Views/Shared/EditorTemplates/Address.ascx) and the name should be the same as the name of the class (Address). ASP.NET MVC will take care of rendering the template for each element of the Addresses collection of your model.

0

精彩评论

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