Reputation: 399
View
@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>
}
Controller
[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(IEnumerable<album> album)
{
}
Is it possible? I want to create a multiple values to database in a faster and easy way.
Upvotes: 1
Views: 2808
Reputation: 399
Thanks for all answers, this informations did get to a single point that worked for me.
@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>
}
Controller
[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FeatureSystem(IEnumerable<album> albums)
Upvotes: 0
Reputation: 38598
Try something like this on your form view, you have to set the index of the collection:
@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>
}
on your controller just do something like:
[HttpPost]
public ActionResult Create(IEnumerable<album> album)
{
if (ModelState.IsValid)
{
// persist and redirect... whatever
}
return View(album);
}
Take a look at this article: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
Upvotes: 1
Reputation: 56429
It is possible, but not like that.
First off, create a model that'll hold your Albums, like so:
public class AlbumsModel
{
public List<Album> Albums { get; set; }
}
Then do the following in your view. Note my use of a for
loop, this is so the name
attributes of the items are in sync and model binding can easily resolve the collection on post.
@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>
}
Then have your Post
controller action be:
[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
}
Upvotes: 2