【发布时间】:2013-05-24 06:55:20
【问题描述】:
我有一个 ASP MVC 3 页面,它允许用户创建一个下拉列表并动态地向其中添加项目。例如,这是页面首次加载时的外观。
左侧的信息用于指定下拉列表将位于哪个页面(Navbar Item)以及我们将为下拉列表提供什么名称(显然是Drop Down List Name)。
右侧的信息(Allowed Value 和Display Value)将是特定的下拉列表项。当用户点击Add Another 链接时,Ajax 调用会转到控制器,返回一个局部视图,然后将其附加到Drop Down Items <fieldset>,如下所示:
问题是,一旦用户点击Submit 按钮,所有项目都无法进入控制器。
我对 ASP MVC 还比较陌生,所以我想知道我是否会以正确的方式进行处理。这是将项目动态添加到列表的正确方法吗?
这是这个视图最初是如何在控制器中创建的
public ActionResult NewList()
{
List<DropDownValues> drop = new List<DropDownValues>();
drop.Add(new DropDownValues());
return View(drop);
}
一个DropDownValues类型的列表被创建并发送到视图,该视图在顶部有这个标签
@model IEnumerable<Monet.Models.DropDownValues>
下面的 Ajax 调用
<script>
$(document).ready(function () {
$("#addItem").click(function () {
if ($('#Field').text() != "" && $('#DisplayPage').text() != "") {
$.ajax({
url: '@Url.Action("BlankDropDownItem", "DropDownValues")',
data: { field: $('#Field').val(), displayPage: $('#DisplayPage').val() },
dataType: 'html',
cache: false,
success: function (html) {
$("#items").append(html);
}
});
} else {
alert("Please enter a Drop Down List Name and Navbar Item first!");
}
return false;
});
});
</script>
调用此控制器方法
public ActionResult BlankDropDownItem(string field, string displayPage)
{
DropDownValues partial = new DropDownValues();
partial.Field = field;
partial.DisplayPage = displayPage;
return PartialView("DropDownItemPartial", partial);
}
然后将此部分视图附加到主页
@model Monet.Models.DropDownValues
@Html.HiddenFor(model => model.Field)
@Html.HiddenFor(model => model.DisplayPage)
<div class="editor-label">
@Html.LabelFor(model => model.AllowedValue)
</div>
<div class="label-field">
@Html.EditorFor(model => model.AllowedValue)
@Html.ValidationMessageFor(model => model.AllowedValue)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.DisplayValue)
</div>
<div class="label-field">
@Html.EditorFor(model => model.DisplayValue)
@Html.ValidationMessageFor(model => model.DisplayValue)
</div>
我正在尝试使用隐藏字段以确保所有新项目都以正确的 Field 和 Navbar Item 值存储在数据库中(再次,不确定这是否是正确的方法对这个)。
任何意见/建议将不胜感激。谢谢!
【问题讨论】:
标签: asp.net-mvc asp.net-mvc-3 razor partial mvc-editor-templates