0

I have the following class...

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public IList<SizeOption> SizeOptions { get; set; }
    public IList<ColorOption> ColorOptions { get; set; }
    public IList<Product> SimilarProduct  { get; set; }
}

I won't elaborate on the details of each of those additional classes. What is important is that a Product contains multiple properties that are child collections.

I'm developing an ASP.NET MVC3 (Razor) web application to help manage these products.

The UI must function in such a way that I have one area for editing the low level product details (Id, Name, Price, etc.) followed by separate areas below for each child collection on Product. (the client wants to manage everything about a product in one screen).

Those areas each have an "Add" button, which creates a new dynamic row with textboxes and various select/checkbox elements so the user can specify options for that object. The user can add/remove these rows of child objects as much as they need to...this is all happening client side with the help of jQuery. Nothing is saved until they submit the form.

What I'm having trouble with is how best to design the layers involved.

Currently, I have a partial view for the Edit Form which is used by the Add Product and Edit Product views. This partial view leverages JavaScript functions to create the dynamic rows. The markup for those dynamic rows is created in these functions in this fashion:

var newRow = $('<tr>').append(...) // etc.
table.append(newRow);

The problem with this approach, is that when I load the Edit Product view, I'm writing the existing child rows using MVC by iterating over the Model's child collections and outputting HTML markup for the rows. For example...

@foreach(var sizeOption in Model.SizeOptions)
{
     <tr>... etc.</tr>
}

This means that I'm duplicating the UI for the rows...I don't like this. I've tried serializing the Model to Json, and calling the client functions based on the data in the Json object, to keep the UI code in one place, but this produces visible latency, which I also do not like.

Lastly, to keep MVC Happy, when the form is finally posted, I iterate the HTML tables and update the Name attributes of the form elements to be in the form of Product.SizeOptions[0].PropertyName so that the MVC View Engine will give a fully hydrated View Model as an argument for my Action methods.

Ultimately I'm looking for advice on how to handle this type of dynamic adding/editing in a scalable and maintainable fashion.

Thanks in advance for the help!

4

1 回答 1

2

您可能会发现以下博客文章很有趣。在其中 Steven Sanderson 说明了一种很好的技术,它允许在 ASP.NET MVC 中动态编辑可变长度列表。它使用自定义帮助器,允许生成输入字段的正确名称,以便默认模型绑定器能够在提交表单时成功检索值。就添加行而言,他使用 AJAX 调用控制器操作,该操作呈现部分视图,该部分视图只是添加到 DOM 中。

于 2012-05-23T20:30:20.177 回答