如何通过javascript从动态添加的文本框中保存多个数据?我已经为产品列表和付款条件动态添加了文本框。我该怎么做控制器和视图
我有测试This,但没有工作
这是我的控制器
public ActionResult Create([Bind(Include = "PurchaseInvoiceTable,PurchaseInvoiceDetailsTable,PaymentTerm")]InvoiceWrapper model)
{
try
{
if (ModelState.IsValid)
{
db.PurchaseInvoiceTables.Add(model.PurchaseInvoiceTable);
db.SaveChanges();
var PID = model.PurchaseInvoiceTable.PurchaseInvoiceID;
model.PurchaseInvoiceDetailsTable.InvoiceID = PID;
model.PaymentTerm.InvoiceID = PID;
db.PurchaseInvoiceDetailsTables.Add(model.PurchaseInvoiceDetailsTable);
db.PaymentTerms.Add(model.PaymentTerm);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.InvoiceID = new SelectList(db.PurchaseInvoiceTables, "PurchaseInvoiceID", "PurID", model.PurchaseInvoiceDetailsTable.InvoiceID);
ViewBag.InvoiceID = new SelectList(db.PurchaseInvoiceTables, "PurchaseInvoiceID", "PurID", model.PaymentTerm.InvoiceID);
return View(model);
}
catch (DbEntityValidationException e)
{
//catch validation here
}
}
这是我的invoiceWrapper
using System;
using System.Collections.Generic;
namespace OnlineInvoiceSystem.Models
{
public class InvoiceWrapper
{
public PurchaseInvoiceTable PurchaseInvoiceTable { get; set; }
public PurchaseInvoiceDetailsTable PurchaseInvoiceDetailsTable { get; set; }
public PaymentTerm PaymentTerm { get; set; }
}
}
这是我的javascript You can test it on Jsfiddle
我的观点是这个
@model OnlineInvoiceSystem.Models.InvoiceWrapper
@{ Layout = null; Layout = "~/Views/Shared/_Layout.cshtml"; }
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
<form>
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<h2>Product List</h2>
<div class="panel panel-default product_wrapper">
//dynamic added textbox will appear here
</div>
<button class="add_field_button btn btn-primary pull-right">Add More Fields</button>
<div class="wrapper-payment-details">
<tr style="background-color:black; color:white;" class="payment_term_wrapper">
// here is the dynamic added payment terms textbox
</tr>
</div>
<div class="form-group">
<div>
<input type="submit" value="Create" class="btn btn-primary pull-right" /> @Html.ActionLink("Back", "Index", null, new { @class = "btn btn-small btn-danger pull-right", @style = "margin-right:2%;" })
</div>
</div>
</form>
}
答案 0 :(得分:0)
你应该建模
@ Html.TextBoxFor(m =&gt; m.PurchaseInvoiceID,new {id =“PurchaseInvoiceID”,@ class =“form-control”})
@ Html.TextBoxFor(m =&gt; m.InvoiceID,new {id =“InvoiceID”,@ class =“form-control”})
然后通过ajax或post json传递此变量
答案 1 :(得分:-1)
你应该使用javascript ajax(POST调用),json包含所有动态添加的字段(作为项目值对象的列表),在服务器端你需要一个可以处理列表的action方法,你不能直接从MVC那里做。