I would like to create multiple objects from one view (e.g. 5 Items in one View). My View looks like:
@model IEnumerable<WerehouseProject.Models.ItemRentList>
@{
ViewBag.Title = "Create";
}
<h2>Dodaj</h2>
@{Html.RenderPartial("_PartialError");}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@for (int i = 0; i < Model.Count; i++)
{
<div class="form-group">
@Html.LabelFor(model => model[i].ItemID, "Przedmiot", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("ItemID", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model[i].ItemID, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model[i].Ilosc, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model[i].Ilosc, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model[i].Ilosc, "", new { @class = "text-danger" })
</div>
</div>
@Html.HiddenFor(model => model[i].ItemRentID)
}
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Dodaj" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
<button type="button" name="ID" value="@ViewBag.ItemRentID" onclick="location.href='@Url.Action("Details", "ItemRents", new { ID = @ViewBag.ItemRentID })'">Wróć</button>
</div>
Create GET method:
public ActionResult Create(int ID, int quantity)
{
var model = new List<ItemRentList>();
for(int i = 0; i < quantity; i++)
{
model.Add(new ItemRentList { ItemRentID = ID } );
}
ViewBag.ItemRentID = ID;
ViewBag.ItemID = new SelectList(db.Items, "ItemID", "Nazwa");
return View(model);
}
And my POST Create method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "IRListID,Ilosc,ItemRentID,ItemID")] IEnumerable<ItemRentList> itemRentList)
{
...
}
My itemRentList.ItemID is always 0, can someone tell me how should I code View or Controller to get list of ItemRentList in POST Method?
This is my Model of ItemRentList
public class ItemRentList
{
[Key]
public int IRListID { get; set; }
[Display(Name = "Ilość")]
public double Ilosc { get; set; }
[Display(Name = "Nazwa przedmiotu")]
public int ItemID { get; set; }
public virtual Item Item { get; set; }
public int ItemRentID { get; set; }
public virtual ItemShopping ItemRent { get; set; }
}
If I edit View and Controller to create only one and always one ItemRentList (not one object in list, just simple ItemRentList) then the value of ItemID is correctly bind to object, the problem is when I want to create a list of ItemRentList, then ItemID is always 0, no mater what I choose from DropDownList.