For循环中的MVC枚举模型绑定

时间:2014-09-25 06:36:15

标签: c# asp.net-mvc html-helper

我有一个MVC 5应用程序,我正在使用for循环,所以我可以在传回控制器时绑定一个集合。这适用于我的所有属性,除了基于DropDownFor类型的属性。

问题是该属性的名称未设置为“product。[0] .TypeOfSubscription。

我尝试了3种不同的方法:前2个方法的最终名称为[0] .TypeOfSubscription,第3个方法的名称正确为产品[0] .TypeOfSubscription但是当我通过它时没有绑定回到控制器。

我认为问题在于第3个选项是绑定,但因为它是隐藏的,所以没有分配选定的值。

@Html.EnumDropDownListFor(modelItem => Model[i].TypeOfSubscription)

@Html.EnumDropDownListFor(modelItem => Model[i].TypeOfSubscription, 
                                            new { name = "product[" + @i + "].TypeOfSubscription"})

@Html.Hidden("product[" + @i + "].TypeOfSubscription",
                                            Model[i].TypeOfSubscription)

模型

public class VmStoreProducts
    {
        public VmStoreProducts()
        {
            NoOfUsers = 1;
        }

        public enum SubscriptionType
        {
            Monthly,
            Annual

        }
        public int MojitoProductId { get; set; }
        [Display(Name = "Category")]
        public string ProductCategory { get; set; }
        public virtual string Name { get; set; }
        public string Description { get; set; }
        [Display(Name = "Image")]
        public byte[] ImageData { get; set; }
        [Display(Name = "Type of Subscription")]
        public SubscriptionType TypeOfSubscription { get; set; }
        public decimal Price { get; set; }
        [Display(Name = "No. of Users")]
        public int NoOfUsers { get; set; }

        [Display(Name = "Total Price")]
        [DisplayFormat(DataFormatString = "{0:C}")]
        public decimal TotalPrice { get; set; }


    }

For Loop - View

@model PagedList.IPagedList<VmStoreProducts>
@using Mojito.Domain
@using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Mojito Products</h2>
<div class="col-md-9"></div>
<div class="col-md-3">
    @using (Html.BeginForm("Index", "MojitoProducts", FormMethod.Get))
    {
        <p>
            @Html.TextBox("SearchString", ViewBag.CurrentFilter as string)
            <input type="submit" value="Search" />
        </p>
    }
</div>
@using (Html.BeginForm("AddToCart", "ShoppingCart", FormMethod.Post))
{
    <table class="table">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.FirstOrDefault().ImageData)
            </th>
            <th>
                @Html.ActionLink("Category", "Index", new { sortOrder = ViewBag.SortByCategory, currentFilter = ViewBag.CurrentFilter })
            </th>
            <th>
                @Html.ActionLink("Product", "Index", new { sortOrder = ViewBag.SortByProduct, currentFilter = ViewBag.CurrentFilter })
            </th>
            <th>
                @Html.DisplayNameFor(model => model.FirstOrDefault().Description)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.FirstOrDefault().TypeOfSubscription)
            </th>
            <th>
                @Html.ActionLink("Price", "Index", new { sortOrder = ViewBag.SortByPrice, currentFilter = ViewBag.CurrentFilter })
            </th>
            <th>
                @Html.DisplayNameFor(model => model.FirstOrDefault().NoOfUsers)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.FirstOrDefault().TotalPrice)
            </th>

            <th></th>
        </tr>

        @for (int i = 0; i < Model.Count; i++)
        {

            <tr>
                <td>
                    @if (Model[i].ImageData != null)
                    {
                        <div class="pull-left" style="margin-right: 10px">
                            <img class="img-thumbnail" width="75" height="75"
                                 src="@Url.Action("GetImage", "MojitoProducts",
                                          new { Model[i].MojitoProductId })" />
                        </div>
                    }
                </td>
                <td>
                    @Html.DisplayFor(modelItem => Model[i].ProductCategory)
                </td>
                <td>
                    @Html.TextBox("product[" + @i + "].Name",
                                Model[i].Name, new { @readonly = "readonly" })
                </td>
                <td>
                    @Html.DisplayFor(modelItem => Model[i].Description)
                </td>
                <td>
                    @Html.EnumDropDownListFor(modelItem => Model[i].TypeOfSubscription)

                    @Html.EnumDropDownListFor(modelItem => Model[i].TypeOfSubscription, 
                                            new { name = "product[" + @i + "].TypeOfSubscription"})

                    @Html.TextBox("product[" + @i + "].TypeOfSubscription",
                                         Model[i].TypeOfSubscription, new { hidden=true })
                </td>
                <td>
                    @Html.TextBox("product[" + @i + "].Price",
                        Model[i].Price, new { @readonly = "readonly", style = "width:50px" })
                </td>
                <td>
                    @Html.TextBox("product[" + @i + "].NoOfUsers",
                        Model[i].NoOfUsers, new { type = "number", min = "0", style = "width:50px" })
                </td>
                <td>
                    @Html.TextBox("product[" + @i + "].TotalPrice",
                        Model[i].TotalPrice, new { style = "width:50px" })
                </td>
                <td>
                    <div class="pull-right">
                        @if (Request.Url != null)
                        {
                            @Html.Hidden("product[" + @i + "].MojitoProductId",
                                      Model[i].MojitoProductId)
                            @Html.Hidden("returnUrl", Request.Url.PathAndQuery)
                        }

                    </div>

                </td>
            </tr>
        }
        <tr>
            <td colspan="6">
                <div class="pull-right">
                    <input type="submit" class="btn btn-success" value="Add to cart" />
                </div>
            </td>
        </tr>



    </table>

}

控制器方法

public ActionResult AddToCart(List<VmStoreProducts> product, string returnUrl)
        {
            ShoppingCart cartObjects = (Session["CartObjects"] as ShoppingCart) ?? new ShoppingCart();
            Session["CartObjects"] = cartObjects;

            foreach (var item in product)
            {
                if (item.NoOfUsers > 0)
                {
                    cartObjects.AddItem(item);
                }

            }

            return RedirectToAction("Index", new { returnUrl });
        }

3 个答案:

答案 0 :(得分:1)

将枚举的定义移到VmStoreProducts

之外
public enum SubscriptionType
{
  Monthly,
  Annual
}

public class VmStoreProducts
{
  public VmStoreProducts()
  {
    NoOfUsers = 1;
  }
  public int MojitoProductId { get; set; }
  ....
}

for循环将命名选择

[0].TypeOfSubscription
[1].TypeOfSubscription
....

将在回发时正确绑定(假设您的操作方法为public ActionResult AddToCart(IEnumerable<VmStoreProducts> products) {...

另外,请勿使用

@Html.TextBox("product[" + @i + "].Name", Model[i].Name, new { @readonly = "readonly" })

由于您已经对同一属性使用了DisplayFor,因此隐藏输入似乎更合适,所以

@Html.HiddenFor(m => m[i].Name)

或者如果您想要显示两次

@Html.TextBoxFor(m => m[i].Name, new { @readonly = "readonly" })

这同样适用于其他属性

答案 1 :(得分:0)

尝试使用文本框并将其隐藏以保留值或使用其他“数据属性”

答案 2 :(得分:-1)

在DropDownListFor的情况下,当数据被发布回控制器时,选定的值会丢失,所以我们需要一个隐藏的文本框来保留选定的值