0

我正在编辑一个复杂类型(AddEventViewModel)。

AddEventViewModel 有一个名为 EventContactList 的 EventContact 列表。

我有一个 EventContactList 的编辑器模板,它为模型中列表中的每个项目显示一个 EventContact。

初始化 AddEventViewModel 时,它将向列表中添加一个空的 EventContact,这意味着在添加事件页面上会显示一个编辑器模板。

在编辑器模板下,我有一个名为“添加其他事件联系人”的按钮。

我想要这个按钮来更新 AddEventViewModel,向 EventContactList 添加一个额外的 EventContact,以便页面将在页面上为新的空 EventContact 显示第二个编辑器模板。

我不想触发验证规则,也不想让用户失去滚动位置,这可能吗?

4

3 回答 3

1

您也可以考虑克隆现有字段、清除值并使用 javascript更改名称。这会更快,因为您不必向服务器询问新的联系人。

例子:

<ul id="ContactsList">
 <li class="newContact">Contact Name :
     <input type="text" name="Contacts[0].Name" value="">
         Email : 
     <input type="text" name="Contacts[0].Email" value="">
 </li>
</ul>

jQuery 添加到您的按钮单击事件中,例如:

var cln = $('li.newContact:first').clone();
var nextNumber = $("#ContactsList li").size();
$("input[name]", cln).each(function() {
    var nm = $(this).attr("name").replace(/\[(.+)\]/g, "[" + nextNumber + "]") ;
    $(this).prop("name", nm);
    $(this).val("");
});
cln.appendTo('#ContactsList');
于 2013-08-28T00:51:03.027 回答
1

感谢您的回答,我花了很多时间研究使用淘汰赛或手工编码 javascript 来实现预期结果的可能性,但是,对于如此微不足道的事情,感觉需要做很多工作。

我现在已经以我认为最简单的方式解决了这个问题,首先我在表单中添加了一个按钮,它将使用 AJAX 添加一个新的编辑器模板。

@Ajax.ActionLink("Add additional contact",
                    "AddContact",
                    "Event",
                    new AjaxOptions()
                        {
                            HttpMethod = "GET",
                            InsertionMode = InsertionMode.InsertBefore,
                            UpdateTargetId = "contacts"
                        })

接下来我将 AddContact actionresult 添加到视图以返回部分视图结果(编辑模板)

public ActionResult AddContact()
{
    return PartialView("EditorTemplates/EventContactDto", new EventContactDto());
}

虽然这会将模板添加到页面中,但在提交表单时不会将其添加到模型中(因为 ID 不正确,因此不会添加到列表中)。

为了解决这个问题,我使用了可以从 Nuget 下载的 Steven Sandersons BeginCollectionItem Helper。

安装包后,我需要做的就是将以下内容添加到编辑器模板中,以便它使用 MVC 的约定设置 ID:

@using (Html.BeginCollectionItem("EventContactList"))
{
... the form ...
}

现在,当页面提交时,模型中的新联系人已准备好插入数据库。

我希望这个答案能帮助其他人,并节省他们研究这个问题的时间!

于 2013-08-28T11:50:47.543 回答
0

Don't you just need a controller to make the insert, and an ajax handler to render the result to the page?

Without more code, it is hard to say exactly how you should do this.

You could also use knockout or backbone to "observe" the variables and update/add template HTML in place. Then you just pass in a new view model, and when you get the one back (with a primary key etc.) you render that in your view.

于 2013-08-27T23:19:08.567 回答