查看仅传递第一个值MVC

时间:2015-05-16 20:57:31

标签: asp.net-mvc

我的项目需要一些帮助。 它是我的ViewModel:

public class ServiceView
{
    public IList<Service> Services { get; set; }
}

动作:

public Actionresult Swap()
{
    var services = from proj in db.Service select proj;
            ServiceView model = new ServiceView();
            model.Services = services.ToList();
            return View(model);
}

查看显示服务的位置:

@model proj.Models.ServiceView
@using(Html.BeginForm("SelectServices" , "AdditionalServices"))
{
    for (int i = 0; i < Model.Services.Count; i++)
    {
        <td>Name: @Html.DisplayFor(m => Model.Services[i].Name) </td>
        <td>Price:@Html.DisplayFor(m => Model.Services[i].Price)</td>
        <td>
            @Html.HiddenFor(m => Model.Services[i].Name)
            @Html.HiddenFor(m => Model.Services[i].Price)
            <input type="submit" id="submit" name="submit" value="Add"/>
        </td>
    }
}

后行动:

[HttpPost]
public ActionResult SelectServices(ServiceView serviceView)
{
    for (int i = 0; i < serviceView.Services.Count; i++)
    {
        return RedirectToAction("Pool", "Rank",
            new
            {
            serviceName = serviceView.Services[i].Name,
            servicePrice = serviceView.Services[i].Price,
    });
}

serviceName = serviceView.Services[i].Name我总是只有第一个元素。为什么?我的错是什么?

1 个答案:

答案 0 :(得分:-1)

您需要做一些工作来帮助模型绑定器进行收集。在视图中使用以下语法来创建隐藏字段。

    @Html.Hidden("[" + i + "].Name", Model.Services[i].Name)
    @Html.Hidden("[" + i + "].Price", Model.Services[i].Price)

然后在你的帖子操作方法中,你需要收到集合

public ActionResult SelectServices(IList<Services> services)
{
   foreach(var sv in services)
    {
                    return RedirectToAction("Pool", "Rank",
                        new
                        {
                        serviceName = sv.Name,
                        servicePrice = sv.Price,
                        });
     }

}