.NET MVC - 提交相同类型的多个模型一次 [英] .NET MVC - Submitting multiple models of the same type at once

查看:137
本文介绍了.NET MVC - 提交相同类型的多个模型一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我已经得到了pretty简单的场景,但似乎无法掌握如何做到这一点在.NET的MVC框架。在其最简单的,这是具有人排名的形式。我想有每个人的姓名和旁边的一个页面上列出他们的名字一个文本框。这里是(剃刀)HTML是什么样子:

I think I've got a pretty simple scenario 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?

推荐答案

我没有用一个Customer对象一个简单的例子,但我认为这是类似的。注意表单域的标记方式。 prefixed与在控制器动作参数的名称。指数需要治疗作为一个集合。因为你有一个嵌套类你可能会稍微复杂一些。 (投票内部人)。我觉得做客户[@counter]表单域.Person.Id会的工作,虽然。对不起,我没有与选票的例子。 :)

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. :)

这将是观的相关部分:

@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);
}

这篇关于.NET MVC - 提交相同类型的多个模型一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆