开发者

.NET MVC - Submitting multiple models of the same type at once

I think I've got a pretty simple scenari开发者_Go百科o but can't seem to grasp how to do it in .NET's MVC framework. At its simplest, this is a form that has people with a ranking. I'd like to have each person's name and a textbox next to their name listed on one page. Here's what the (Razor) Html looks like:

@using (Html.BeginForm()) {
<fieldset>
    @foreach (var b in Model.Ballots) {
        <p>
            <label>@b.Person.FullName</label>
            @Html.TextBox("Rank")
            @Html.ValidationMessage("Rank")
        </p>
    }
</fieldset>
 <input type="submit" value="Vote" />

}

A ballot is a simple object that has a person and a ranking:

public class Ballot {
    public Person Person { get; set; }
    [Range(1, 6, ErrorMessage="The voting range is 1 through 6")]
    public int Rank { get; set; }
}

Here's my controller's method for handling the form submission, but it never gets called.

[AcceptVerbs("POST")]
    public ActionResult Vote(IEnumerable<Ballot> ballots) {

        return View("BallotComplete");
    }

How do I go about iterating all the models that the form submits back to the server?


I did a quick example using a Customer object, but I think it's similar. Note how the form fields are labeled. Prefixed with name of parameter in action in controller. Index is needed to treat as a collection. Yours might be slightly more complex, because you have a nested class. (Person inside of ballot). I think by doing customers[@counter].Person.Id for form fields would work though. Sorry I didn't have an example with ballots. :)

This would be the relevant part of the View:

@using (Html.BeginForm())
{
    var counter = 0;
    foreach (var customer in this.Model)
     {
         <input type="text" name="customers[@counter].Id" value="@customer.Id"/>
         <input type="text" name="customers[@counter].CompanyName" value="@customer.CompanyName"/>
         counter++;
     }
     <input type="submit" />
}

and this would be the relevant part of the controller:

public ActionResult Test()
{
    return View(Service.GetCustomers());
}

[HttpPost]
public ActionResult Test(Customer[] customers )
{
    return View(customers);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜