我想通过单击添加按钮动态添加文本框,可以删除文本框,最后可以保存文本框中的列表值。
我的模特班
public class CustModel
{
public List<Cust> CustList { get; set; }
}
public class Cust
{
public string Name { get; set; }
}
My controller class
public class HomeController : Controller
{
private DB _entities;
public HomeController()
{
_entities = new DbEntities();
}
public ActionResult Index()
{
return View(_customers);
}
[HttpPost]
public ActionResult Index(CustModel model)
{
// save to the database
return View();
}
}
我想知道.cshtml代码。或任何其他将列表项提交到数据库的建议。
我会这样做:
在 CustModel 中,我将属性更改为 IEnumerable。我将使用 EditorTemplate for Cust,这将节省额外的循环。
public class CustModel
{
public IEnumerable<Cust> CustList { get; set; }
}
我的 Index.cshtml 视图很简单,我已经声明了强类型模型,然后以我的形式@Html.EditorFor
对于 Custlist,有一个用于添加新客户的按钮、一个用于提交的按钮以及用于添加新客户的 JQuery 脚本。请注意,在 jquery 中,我创建了控件数组,以便模型绑定器可以正确选择它们。
索引.cshtml
@model MvcApplication2.Models.CustModel
@{
ViewBag.Title = "Home Page";
}
@using (Html.BeginForm()) {
<fieldset>
<legend></legend>
<div id="divcust">
@Html.EditorFor(m=>m.CustList)
</div>
<input id="btnAdd" type="button" value="Add Cust" onclick="AddCust();" />
<br />
<br />
<input type="submit" value="Submit" />
</fieldset>
}
<script>
function AddCust() {
var m = $('#divcust input:last-child').attr('name');
var index = 0;
if (m != null && m.length > 0) {
index = m.split('CustList[')[1].replace('].Name', '');
index++;
}
var html = '<label for=\"CustList_' + index + '__Name\">Name</label>' +
'<input id=\"CustList_' + index + '__Name\" class=\"text-box single-line\"' +
' type=\"text\" value=\"\" name=\"CustList[' + index + '].Name\">';
$('#divcust').append(html);
};
</script>
我在 view/home 文件夹中添加了一个 EditorTemplates 文件夹,并为 Cust 添加了一个视图:
客户.cshtml
@model MvcApplication2.Models.Cust
@Html.LabelFor(m=>m.Name)
@Html.EditorFor(m=>m.Name)
现在一切正常,我可以添加新的囊肿并将其发布以保存。
如果我想添加删除功能,我必须小心保持控制数组的完整性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)