这是我的控制器操作方法Calculate
public ActionResult Calculate(List<BOM> bl )
{
ViewBag.Category = new SelectList(db.Category, "ID", "Type");
if (ModelState.IsValid)
{
foreach (var i in bl)
{
db.BOM.Add(i);
}
db.SaveChanges();
}
return View();
}
和行动方法的视图
@model List<My_Inventory.Models.BOM>
@{
ViewBag.Title = "Calculate";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm())
{
<fieldset>
@Html.AntiForgeryToken()
<table class="table">
<tr>
<th>@Html.LabelFor(model => model.Category, htmlAttributes: new { @class = "category" })</th>
<th>@Html.LabelFor(model => model.Make, htmlAttributes: new { @class = "brand" })</th>
<th>@Html.LabelFor(model => model.Item, htmlAttributes: new { @class = "Category" })</th>
<th>@Html.LabelFor(model => model.Quantity, htmlAttributes: new { @class = "PQuantity" })</th>
<th>@Html.LabelFor(model => model.Unit_Cost, htmlAttributes: new { @class = "Unit" })</th>
<th>@Html.LabelFor(model => model.Total_Cost, htmlAttributes: new { @class = "Total" })</th>
</tr>
@for (int i = 0; i < 20; i++)
{
<tr>
<td>
@Html.DropDownListFor(model => model.Category, ViewBag.Category as SelectList, "Select", new { @id = "ddlSelect" + i, @class = "category", onchange = "Getoption(" + i + ");" })
@Html.ValidationMessageFor(model => model.Category, "", new { @class = "text-danger" })
</td>
<td>
@Html.DropDownListFor(model => model.Make, new SelectList(Enumerable.Empty<SelectListItem>(), "Value", "Text"), "Select", new { @id = "ddlsub" + i, @class = "brand", onchange = "GetProducts(" + i + ");" })
@Html.ValidationMessageFor(model => model.Make, "", new { @class = "text-danger" })
</td>
<td>
@Html.DropDownListFor(model => model.Item, new SelectList(Enumerable.Empty<SelectListItem>(), "Value", "Text"), "Select", new { @id = "ddlProduct" + i, @class = "Product" })
@Html.ValidationMessageFor(model => model.Item, "", new { @class = "text-danger" })
</td>
<td>
@Html.TextBoxFor(model => model.Quantity, new { @id = "TextQuantity" + i, @class = "PQuantity", onblur = "Calculatecost(" + i + ");" })
@Html.ValidationMessageFor(model => model.Quantity, "", new { @class = "text-danger" })
</td>
<td>
@Html.LabelFor(model => model.Unit_Cost, "UnitCost", new { @id = "Ucost" + i, @class = "Unit" })
@Html.ValidationMessageFor(model => model.Quantity, "", new { @class = "text-danger" })
</td>
<td>
@Html.LabelFor(model => model.Total_Cost, "TotalCost", new { @id = "TotalCost" + i, @class = "" })
@Html.ValidationMessageFor(model => model.Quantity, "", new { @class = "text-danger" })
</td>
</tr>
}
</table>
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
我正在将多行数据从视图传递到控制器,以便将它们保存到数据库中,但它会抛出错误&#34;对象引用未设置为对象的实例。&#34; 有什么建议......怎么回事?
答案 0 :(得分:0)
首先,您没有将模型传递给Controller中的视图,它应该是return View(bl);
而不是简单的return View();
其次,既然你没有将它传递给你的View,它就不会被设置,因此Model是null。
第三,您传递List
作为模型,并在视图中将其作为单个对象访问。请检查您的代码并重新发布。