【发布时间】:2015-09-11 17:43:46
【问题描述】:
正如你在图片中看到的,我有一个表格,我不断地向下表中添加项目。
当我单击“全部保存”按钮时,它会将所有表值发布到“InsertBulk”方法。
在我看来,这就是我所做的。我在表格中创建了一个表格。为每个输入字段设置名称和值。隐藏输入字段,仅显示文本,然后单击 save all 按钮将所有这些值发布到 InsertBulk 方法。
@model FYPPharmAssistant.Models.InventoryModel.Manufacturer
@{
ViewBag.Title = "Form";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm())
{
<label>Name</label><br />
@Html.EditorFor(m => m.ManufacturerName, new { htmlAttributes = new { @class = "form-control" } }) <br />
<label>Description</label><br />
@Html.EditorFor(m => m.Description, new { htmlAttributes = new { @class = "form-control" } })
<input type="submit" id="addmore" value="add" />
}
@using (Html.BeginForm("InsertBulk", "Manufacturer"))
{
<table id="table">
<tr>
<th>
name
</th>
<th>
description
</th>
</tr>
</table>
<input type="submit" id="btnsaveall" value="Save all" />
}
<script>
$(document).on('ready', function () {
$('#addmore').on('click', function () {
var $table = $("#table");
$table.append("<tr> <td><input type='hidden' name='ManufacturerName' value='" + $('#ManufacturerName').val() + "' />" + $('#ManufacturerName').val() + "</td> <td><input type='hidden' name='Description' value='" + $('#Description').val() + "'>" + $('#Description').val() + "</td> <td><a href='javascript:void(0)' onclick='removeItem(this)'>Remove</a></td></tr>");
return false;
});
});
</script>
这是我的 InsertBulk 方法。
[HttpPost]
public void InsertBulk(FormCollection coll)
{
Manufacturer m = new Manufacturer();
m.ManufacturerName = coll["ManufacturerName"];
m.Description = coll["Description"];
db.Manufacturers.Add(m);
db.SaveChanges();
}
结果: Ans 这就是我在结果中得到的。我想怎么解决这个问题?请帮忙!
我还尝试在 InsertBulk 方法中计算键并循环遍历每个键。但我觉得我做错了。
int count = coll.Count;
if(count == 0)
{
return View("ChamForm", "Test");
}
else
{
for(int i = 0; i<count; i++)
{
Manufacturer m = new Manufacturer();
m.ManufacturerName = coll["ManufacturerName[" + i + "]"];
m.Description = coll["Description[" + i + "]"];
db.Manufacturers.Add(m);
db.SaveChanges();
}
}*
【问题讨论】:
标签: c# asp.net-mvc formcollection