如何发送一组数据以便将其绑定到Controller的操作中?

问题描述

| 我如何从客户端发送数据以便在“保存”操作中获取数据? 这意味着当我在“保存”操作中获得的联系人列表为空时。 我检查了提琴手,它发送了“ 0”。我意识到我需要做一些事情,以便MVC能够“理解”有2个不同的记录。 在这种情况下,实际上是怎么做的?
// Action in ContactController
public ActionResult Save(List<Contact> contacts)
{
     ...
}  

public class Contact
{
    public int Id {get;set;}
    public string Address{get;set;}
}


// View
<div id=\"contacts\">
    <% for(i=0;i<3;i++) { %>
       <input name=<%= list[i].id %> type=\"text\" />
       <input name=<%= list[i].address %> type=\"text\" />
   <% } %>
</div>


<script type=\"text/javascript\">
     var postData = $(\"#contacts\").serialize();
     $.ajax({
             type: \"POST\",url: url,data: postData,async: false,success: function () { ... }
     });  
</script>
    

解决方法

        我建议您在视图中使用编辑器模板,而不要编写一些for循环: 例如:
public ActionResult Save()
{
    var model = Enumerable.Range(1,3).Select(x => new Contact());
    return View(model);
}

[HttpPost]
public ActionResult Save(List<Contact> contacts)
{
    ...
}
并在视图中(强烈键入
IEnumerable<Contact>
):
<div>
    <% using (Html.BeginForm()) { %>
        <%= Html.EditorForModel() %>
        <input type=\"submit\" value=\"OK\" />
    <% } %>
</div>
并在联系人编辑器模板(
~/View/Shared/EditorTemplates/Contact.ascx
)中:
<%@ Control 
    Language=\"C#\" 
    Inherits=\"System.Web.Mvc.ViewUserControl<Contact>\" 
%>
<%= Html.TextBoxFor(x => x.Id) %>
<%= Html.TextBoxFor(x => x.Address) %>
编辑器模板将确保为输入字段生成适当的名称。 现在剩下的就是AJAXify表单:
$(\'form\').submit(function() {
    $.ajax({
        url: this.action,type: this.method,traditional: true,data: $(this).serialize(),success: function(result) {
            ...
        }
    });
    return false;
});
    ,        在您的示例中,如果将手动创建更改为Html.TextBoxFor
<% Html.TextBoxFor(model => list[i].Address) %>
会的。看看Phil Haack的文章