开发者

How to send group of data so it will be binded in Controller's action?

开发者 https://www.devze.com 2023-03-13 00:42 出处:网络
How I need to send the data from the client in order to get it in Save action? Mean while the contacts list I get in Save action is null.

How I need to send the data from the client in order to get it in Save action?

Mean while the contacts list I get in Save action is null. I checked fiddler and it sends id=1&address=a&id=2&address=b. I realize that I need to do something in order that MVC will "understand" that there are 2 different records.

What is done, in practice, in this case?

// 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",
             开发者_JAVA百科url: url,
             data: postData,
             async: false,
             success: function () { ... }
     });  
</script>


I would recommend you to use editor templates in your view instead of writing some for loops:

For example:

public ActionResult Save()
{
    var model = Enumerable.Range(1, 3).Select(x => new Contact());
    return View(model);
}

[HttpPost]
public ActionResult Save(List<Contact> contacts)
{
    ...
}

and in the view (which is strongly typed to IEnumerable<Contact>):

<div>
    <% using (Html.BeginForm()) { %>
        <%= Html.EditorForModel() %>
        <input type="submit" value="OK" />
    <% } %>
</div>

and inside the contact editor template (~/View/Shared/EditorTemplates/Contact.ascx):

<%@ Control 
    Language="C#" 
    Inherits="System.Web.Mvc.ViewUserControl<Contact>" 
%>
<%= Html.TextBoxFor(x => x.Id) %>
<%= Html.TextBoxFor(x => x.Address) %>

Editor templates will ensure to generate proper names for the input fields.

Now all that's left is AJAXify the form:

$('form').submit(function() {
    $.ajax({
        url: this.action,
        type: this.method,
        traditional: true,
        data: $(this).serialize(),
        success: function(result) {
            ...
        }
    });
    return false;
});


In your example, if you change manual creation to Html.TextBoxFor

<% Html.TextBoxFor(model => list[i].Address) %>

It will work. Take a look at Phil Haack's article

0

精彩评论

暂无评论...
验证码 换一张
取 消