1

看法

@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)
{
}

是否可以?我想以更快、更简单的方式为数据库创建多个值。

4

3 回答 3

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
}
于 2012-12-04T17:27:54.983 回答
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

于 2012-12-04T17:28:19.190 回答
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)
于 2013-02-05T14:52:47.800 回答