mvc Dropdown list with model of type list

2019-09-17 15:25发布

问题:

I am pretty new to MVC however I have been trying to use a dropdownlist in a view which has a model of type List<>. The reason for this is to create multiple records on a single page.

I have been able to successfully create a view that is not of type List<> and a single record at a time, but in spite of a lot of googling can not implement the solution when I implement the view with a model of type List<>.

Model

public class Product
{
    public int ProductID { get; set; }

    public string Description { get; set; }

    public int VatRateID { get; set; }

    [ForeignKey("VatRateID")]
    public virtual VatRate VatRate { get; set; }

}

Controller

    // GET: /Product/Bulkdata
    public ActionResult BulkData()
    {
        PopulateVatRateDropDownList();
        List<Product> model = new List<Product>();
        model.Add(new Product
                        {
                            ProductID = 0,
                            Description = "",
                            VatRateID = 1
                        }
                );
        return View(model);
    }

    //
    // POST: /Product/Bulkdata

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult BulkData(
        [Bind(Include = "Description,VatRateID")]
        List<Product> products)
    {

        try
        {
            if (ModelState.IsValid)
            {
                foreach (var p in products)
                {
                    db.Product.Add(p);
                }
                db.SaveChanges();
                return RedirectToAction("Index");
            }
        }
        catch (DataException)
        {
            ModelState.AddModelError("", "Bulk - Unable to save changes, Try again, and if the probelm persists contact your administrator");
        }
        PopulateVatRateDropDownList();
        return View(products);
    }

    private void PopulateVatRateDropDownList(object selectedVatRate = null)
    {
        var vatRateQuery = from v in db.VatRate
                           select v;
        ViewBag.VatRateID = new SelectList(vatRateQuery, "VatRateID", "VatRateDescription", selectedVatRate);
    }

View

   @if (Model != null && Model.Count > 0)
   {
       int j = 0;
       foreach (var i in Model)
       {

            <tr style="border:1px solid black">
                <td>
                    @Html.EditorFor(m => m[j].Description)
                    @Html.ValidationMessageFor(m => m[j].Description)
                </td>
                <td>
                    @Html.DropDownList("VatRateID", String.Empty)
                    @Html.ValidationMessageFor(m => m[j].VatRateID)
                </td>
                <td>
                   @if (j > 0)
                   {
                        <a href="#" class="remove">Remove</a>
                   }
                </td>
            </tr>
            j++;
       }
   }

When I run the application with this code then 0 is always past back to vatRateID. I have tried numerous other solution other than the above including ASP.NET MVC DropDownListFor with model of type List<string>. As I have mentioned I am new to mvc so I know there is probably something simple that I am missing. Any help would be hugely appreciated.

Thanks

回答1:

Answered by Stephen in comments:

In the view, changed the foreach to a for loop as per the article in Stephen's comment and used DropdDownListFor

@Html.DropDownListFor(m => m[i].VatRateID, (IEnumerable<SelectListItem>)ViewBag.VatRateList)

Also amended the controller to rename the ViewBag property to VatRateList

' private void PopulateVatRateDropDownList(object selectedVatRate = null) { var vatRateQuery = from v in db.VatRate select v; ViewBag.VatRateID = new SelectList(vatRateQuery, "VatRateID", "VatRateDescription", selectedVatRate); } '