Following up on the previous posts, it might be worth thinking about splitting the view and create actions up.
Looking at your original post, it's difficult to see a scenario where you might want to add many items at once (how would the application know how many items you wanted to add?).
So starting with your model class..
namespace Sample.Models
{
using System.ComponentModel.DataAnnotations;
public class Music
{
[Required]
public int Music_Id { get; set; }
[Required]
public string Song_Name { get; set; }
[Required]
public string Music_Director { get; set; }
}
}
..add in two views; Index (to display the current list of music files stored in your data source):
@model List<sample.models.music>
<h1>Music</h1>
<table>
@foreach (var item in Model)
{
<tr>
<td>
@item.Music_Id
</td>
<td>
@item.Song_Name
</td>
<td>
@item.Music_Director
</td>
</tr>
}
</table>
@Html.ActionLink("Add", "Create")
..and Create (to allow a new music file to be defined):
@model Sample.Models.Music
@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { }))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Music</legend>
<div class="editor-label">
@Html.LabelFor(model => Model.Music_Id)
</div>
<div class="editor-field">
@Html.EditorFor(model => Model.Music_Id)
@Html.ValidationMessageFor(model => Model.Music_Id)
</div>
<div class="editor-label">
@Html.LabelFor(model => Model.Song_Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => Model.Song_Name)
@Html.ValidationMessageFor(model => Model.Song_Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => Model.Music_Director)
</div>
<div class="editor-field">
@Html.EditorFor(model => Model.Music_Director)
@Html.ValidationMessageFor(model => Model.Music_Director)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
Then finally update your controller to handle the appropriate actions:
namespace Sample.Controllers
{
using System.Collections.Generic;
using System.Web.Mvc;
using Sample.Models;
public class HomeController : Controller
{
public ActionResult Index()
{
return View(GetData());
}
[HttpGet]
public ActionResult Create()
{
return View(new Music());
}
[HttpPost]
public ActionResult Create(Music model)
{
if (ModelState.IsValid)
{
AddItem(model);
return RedirectToAction("Index");
}
return View(model);
}
private List<music> GetData()
{
if (Session["data"] == null)
{
Session["data"] = new List<music>();
}
return (List<music>)Session["data"];
}
private void AddItem(Music item)
{
var data = GetData();
data.Add(item);
Session["data"] = data;
}
}
}
Note that in the example I've given, I'm just creating a simulated data source as a Session variable.
If you really wanted to add multiple items at once, you could modify the Create action to just add a blank item to your data source and change add a POST Index action to perform an Update on the data instead. Let me know if that's what you're looking for and I'll post that solution here.