Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Editing A Collection Best Practices - Your Opinion

Given the following class, what is your opinion on the best way to handle create/edit where Attributes.Count can be any number.

public class Product {
  public int Id {get;set;}
  public string Name {get;set;}
  public IList<Attribute> Attributes {get;set;}
}

public class Attribute {
  public string Name {get;set;}
  public string Value {get;set;}
}

The user should be able to edit both the Product details (Name) and Attribute details (Name/Value) in the same view, including adding and deleting new attributes.

Handling changes in the model is easy, what's the best way to handle the UI and ActionMethod side of things?

like image 506
Kyle West Avatar asked Nov 14 '08 02:11

Kyle West


2 Answers

Look at Steve Sanderson’s blog post Editing a variable length list, ASP.NET MVC 2-style.

Controller

Your action method receives your native domain model Product and stays pretty simple:

public ActionResult Edit(Product model)

View

Edit.aspx

<!-- Your Product inputs -->
<!-- ... -->

<!-- Attributes collection edit -->
<% foreach (Attribute attr in Model.Attributes)
   {
       Html.RenderPartial("AttributeEditRow", attr);
   } %>

AttributeEditRow.ascx

Pay your attention to helper extension Html.BeginCollectionItem(string)

<% using(Html.BeginCollectionItem("Attributes")) { %>
    <!-- Your Attribute inputs -->
<% } %>

Adding and editing of new attributes is possible too. See the post.

like image 103
Serge S. Avatar answered Nov 15 '22 18:11

Serge S.


Use the FormCollection and iterate through the key/value pairs. Presumably you can use a naming scheme that will allow you to determine which key/value pairs belong to your attribute set.

[AcceptVerbs( HttpVerb.POST )]
public ActionResult Whatever( FormCollection form )
{
 ....
}
like image 3
tvanfosson Avatar answered Nov 15 '22 19:11

tvanfosson