查看创建发送IEnumerable到Controller

时间:2012-12-04 17:18:48

标签: c# .net asp.net-mvc razor asp.net-mvc-4

查看

@model IEnumerable<MyMixtapezServerCodeHomePage.Models.album>

@for(int i=0;i<userchoiceIndex;i++)
{
    <div class="editor-label">
        @Html.LabelFor(model => model.artist)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.artist)
        @Html.ValidationMessageFor(model => model.artist)
    </div>
}

控制器

[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(IEnumerable<album> album)
{
}

有可能吗?我想以更快捷方式为数据库创建多个值。

3 个答案:

答案 0 :(得分:2)

有可能,但不是那样。

首先,创建一个能够保存相册的模型,如下所示:

public class AlbumsModel
{
    public List<Album> Albums { get; set; }
}

然后在您的视图中执行以下操作。请注意我使用for循环,因此项目的name属性是同步的,模型绑定可以轻松解决帖子上的集合。

@model AlbumsModel

@for(int i=0; i<Model.Albums.Count; i++)
{
    <div class="editor-label">
        @Html.LabelFor(m=> m.Albums[i].artist)
   </div>
   <div class="editor-field">
       @Html.EditorFor(m=> m.Albums[i].artist)
       @Html.ValidationMessageFor(m => m.Albums[i].artist)
   </div>
}

然后让您的Post控制器操作为:

[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(AlbumsModel model)
{
    foreach(Album album in model.Albums)
    {
        //do your save here
    }
    //redirect or return a view here
}

答案 1 :(得分:1)

在表单视图中尝试这样的操作,您必须设置集合的索引:

@model IEnumerable<MyMixtapezServerCodeHomePage.Models.album>

@for (int i=0; i<userchoiceIndex; i++)
{
    <div class="editor-label">
        @Html.LabelFor(model => model[i].artist)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model[i].artist)
        @Html.ValidationMessageFor(model => model[i].artist)
    </div>
}
控制器上的

只需执行以下操作:

[HttpPost]
public ActionResult Create(IEnumerable<album> album)
{
    if (ModelState.IsValid) 
    {
       // persist and redirect... whatever
    }
    return View(album);
}

看一下这篇文章:http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

答案 2 :(得分:0)

感谢所有答案,这些信息确实得到了一个对我有用的信息。

@model IEnumerable<MyMixtapezServerCodeHomePage.Models.album>
@using (Html.BeginForm("FeatureSystem", "album", FormMethod.Post))

<th>
    @Html.DisplayNameFor(model => model.name)
</th>

@{var item = @Model.ToList();}
@for (int count = 0; count < @Model.Count(); count++){
    <td>
        <div class="editor-label">
            @Html.LabelFor(model => item[count].name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => item[count].name)
            @Html.ValidationMessageFor(model => item[count].name)
        </div>
</td>
}

控制器

[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FeatureSystem(IEnumerable<album> albums)