Asp.net mvc 4 模型中的mvc集合

Asp.net mvc 4 模型中的mvc集合,asp.net-mvc-4,razor,Asp.net Mvc 4,Razor,我以前从未遇到过这样的情况,我的模型中有一个集合,但我一次只显示一个项目。这里有一个简单的例子 型号: public class MyViewModel { //some other fields public IList<SomeObject> MyCollection { get; set; } } @model MyViewModel <ul> for(int i; i < Model.MyCollection.Count();

我以前从未遇到过这样的情况,我的模型中有一个集合,但我一次只显示一个项目。这里有一个简单的例子

型号:

public class MyViewModel
{
    //some other fields

    public IList<SomeObject> MyCollection { get; set; }
}
@model MyViewModel

<ul>
    for(int i; i < Model.MyCollection.Count(); i++)
    {
        //user can select an item from list and for the chosen item,
        //show fields to edit below

        <li>@Model.MyCollection[i].Name;
    }
</ul>

@Html.LabelFor(m => m.MyCollection[TempData["Index"]].SomeProperty)
@Html.TextBoxFor(m => m.MyCollection[TempData["Index"]].SomeProperty)

//other fields
公共类MyViewModel
{
//其他一些领域
公共IList MyCollection{get;set;}
}
查看:

public class MyViewModel
{
    //some other fields

    public IList<SomeObject> MyCollection { get; set; }
}
@model MyViewModel

<ul>
    for(int i; i < Model.MyCollection.Count(); i++)
    {
        //user can select an item from list and for the chosen item,
        //show fields to edit below

        <li>@Model.MyCollection[i].Name;
    }
</ul>

@Html.LabelFor(m => m.MyCollection[TempData["Index"]].SomeProperty)
@Html.TextBoxFor(m => m.MyCollection[TempData["Index"]].SomeProperty)

//other fields
@model MyViewModel
    对于(int i;i@Model.MyCollection[i].名称; }
@LabelFor(m=>m.MyCollection[TempData[“Index”]].SomeProperty) @Html.TextBoxFor(m=>m.MyCollection[TempData[“Index”]].SomeProperty) //其他领域
这包含在部分视图中的一个表单中,当用户从名称列表中选择一个项目时,该表单将刷新,其选择将反映在
TempData[“Index”]


我的问题是,当我将此信息发布到我的控制器时(该控制器需要
MyViewModel
),内部
MyCollection
的集合将只显示一个项目(以显示的项目为准)。要捕获整个集合,我必须循环遍历整个集合,并为每个不是当前所选对象(它是一个相当复杂的模型)的对象使用隐藏字段,还是有更好的方法来执行此操作?

请记住
ViewModels
不是
ViewState
,从某种意义上讲,所有这些内容都会像Asp.NETWebForms一样发布回服务器

如果在您的场景中,从Controller->View(呈现页面时)到View->Controller(发布时)的信息不同,那么您实际上应该使用两个单独的ViewModel,以不同的方式表示数据

例如,在发布时,您可能只发布所选项目的id,控制器将在内部用整个集合重新创建您的
MyViewModel
(可能来自数据库或类似的东西)

视图应避免发送不是用户实际输入的大型数据集


现在,如果您真的没有其他选择,只能将整个集合从视图重新发送到控制器,那么您必须为每个项目和其中的每个属性创建隐藏的输入元素。

+1我考虑了不同的模型,但找不到一个很好的例子。不幸的是,我确实有用户输入要传回。但是,有没有可能在post上有一个my object的实例而不是collection,或者它总是发送一个包含一个项目的集合?好吧,您可以发布任何您想要的内容。最终,您将声明某个模型作为操作的参数,如果在HTTP Post中,值与参数对象的属性名称匹配,则将由默认绑定器自动创建。请记住,表单发布对对象一无所知,它只发布表单值。它是从这些值中提取viewmodels的默认绑定器。