正如你在图片中看到的那样,我有一个表格,我不断在下表中添加项目。
当我点击“全部保存”按钮时,它会将所有表值发布到“ InsertBulk ”方法。
这就是我在我看来所做的。我在表格中创建了一个表单。设置每个输入字段的名称和值。隐藏输入字段,仅显示文本,然后单击保存所有按钮,将所有这些值发布到 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();
}
结果: 这是我在Result中得到的。我怎么想解决这个问题?请帮忙!
我还尝试计算键并循环遍历 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();
}
}*
答案 0 :(得分:1)
如果是这样,为什么不基于逗号分割内容,将它们中的每一个保存在两个不同的字符串数组中。然后遍历每个数组的项目,在每个循环中保存名称和描述。
答案 1 :(得分:0)
public ActionResult Student(StudentModel model, FormCollection frm)
{
string XmlData = "<Parent>";
var stuclass = frm.GetValues("stuclass");
var InstituteId = frm.GetValues("Institute");
var obtmark = frm.GetValues("obtmark");
var totalmark = frm.GetValues("totalmark");
var per = frm.GetValues("per");
int count = stuclass.Count();
for (int i = 0; i < count; i++)
{
XmlData += "<child><stuclass>" + stuclass[i] + "</stuclass>"
+ "<InstituteId>" + InstituteId[i] + "</InstituteId>"
+ "<obtmark>" + obtmark[i] + "</obtmark>"
+ "<totalmark>" + totalmark[i] + "</totalmark>"
+ "<per>" + per[i] + "</per>"
+ "</child>";
}
XmlData += "</Parent>";
model.XmlData = XmlData;
var res = studal.Insertdtl(model);
return View();
}