简体   繁体   中英

MVC Enum Model Binding in For Loop

I have an MVC 5 app where I am using a for loop so I can bind a collection when passing back to the controller. This works fine for all my properties except for the one that is based on a DropDownFor type.

The problem is the name of the property is not getting set to "product.[0].TypeOfSubscription.

I have tried 3 different ways: The first 2 method end up with a name of [0].TypeOfSubscription and the 3rd one does have the correct name product[0].TypeOfSubscription but there is no binding occuring when I pass it back to the controller.

I think the problem is that the 3rd option is binding but because it is hidden it is not getting the selected value assigned.

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

Model

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>

}

Controller Method

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

Move the definition of the enum outside the VmStoreProducts class

public enum SubscriptionType
{
  Monthly,
  Annual
}

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

The for loop will name the selects

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

which will correctly bind on postback (assuming your action method is public ActionResult AddToCart(IEnumerable<VmStoreProducts> products) {...

Also, do not use

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

Since you already using a DisplayFor for the same property a hidden input seems more appropriate, so

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

or if you want to display it twice

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

This applies to the other properties as well

尝试使用文本框并将其隐藏以保留该值或使用另一个'data-property

对于DropDownListFor,当数据回传到控制器时,所选值会丢失,因此我们需要有一个隐藏的文本框来保留所选值

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM