在列表中添加/删除项目作为视图中模型的属性

时间:2012-08-09 13:07:10

标签: c# asp.net-mvc asp.net-mvc-2

我正在使用http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style中找到的指南并使用MVC2。

我已经使用控制器方法了:

[HttpPost]
public ActionResult CreateStockRequest(StockRequestModel viewModel, List<StockRequestModel.StockRequestItem> items)
{
    viewModel.Items = items;

    // Validate the request and submit it
    return View(viewModel);
}

正如您所看到的,即使我的模型包含Items方法,我也必须添加items参数,因为模型上的属性未填充。

我已尝试在items方法中将Items更改为BeginCollectionItem并尝试了其他各种值,但如果不添加单独的{{1},我就无法使其工作控制器方法中的参数。

tl; dr:如何从视图中添加/删除/编辑模型列表属性中的项目?


视图

items

部分视图

<table>
    <thead>
        <tr>
            <td><%= Html.LabelFor(m => m.Items[0].Item )%></td>
            <td><%= Html.LabelFor(m => m.Items[0].Quantity )%></td>
        </tr>
    </thead>
    <tbody id="editorRows">
        <% foreach (var item in Model.Items)
           {
               Html.RenderPartial("StockRequestItemEditor", item);
        }%>
    </tbody>
    <tfoot>
        <tr><td colspan="2">&nbsp;</td></tr>
        <tr>
            <td colspan="2"><%= Html.ActionLink("Add Item...", "BlankEditorRow", null, new { id = "addItem" })%></td>
            <script type="text/javascript">
                $("#addItem").click(function() {
                    $.ajax({
                        url: this.href,
                        cache: false,
                        success: function(html) { $("#editorRows").append(html); }
                    });
                    return false;
                });
            </script>
        </tr>
    </tfoot>
</table>

2 个答案:

答案 0 :(得分:1)

这是一个很长的镜头,但也许这就是问题所在:

Html.RenderPartial("StockRequestItemEditor", item);

我注意到在POST操作中检查viewModel时它会在集合中拥有正确数量的项目,但它们都将为null。这告诉我,这是模型绑定器的前缀问题。所以也许这样的事情会起作用:

var dictPrefix = new ViewDataDictionary();
dictPrefix.TemplateInfo.HtmlFieldPrefix = "SomePrefix";

Html.RenderPartial("StockRequestItemEditor", item, dictPrefix);

我不认为RenderPartial()在不使用此重载的情况下传递前缀(虽然可能是错误的)。我不完全确定绑定前缀是如何工作的,所以我实际上并不知道名称是什么,但它似乎与此相关。该集合肯定有适合我的项目数量,但没有一个正确绑定。

希望这足以让别人给你正确答案。

答案 1 :(得分:0)

为什么不使用视图模型?

public class StockRequestModel 
{
    public List<StockRequestItem> Items { get; set; }

    ... some other properties
}

然后让控制器操作将此视图模型作为参数:

[HttpPost]
public ActionResult CreateStockRequest(StockRequestModel viewModel)
{
    // TODO: do something with viewModel.Items ...

    return View(viewModel);
}

并在您的视图中:

<div class="editorRow">
    <% using(Html.BeginCollectionItem("Items")) { %>
        ...
    <% } %>
</div>