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?
Look at Steve Sanderson’s blog post Editing a variable length list, ASP.NET MVC 2-style.
Your action method receives your native domain model Product
and stays pretty simple:
public ActionResult Edit(Product model)
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.
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 )
{
....
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With