在MVC 5中填充DropDownList

时间:2015-07-27 07:30:53

标签: c# asp.net asp.net-mvc razor asp.net-mvc-5

以下是我的 AddNewProductViewModel

的代码
using AccessorizeForLess.Data;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web;

namespace AccessorizeForLess.ViewModels
{
    public class AddNewProductViewModel
    {
        public string Name { get; set; }

        [DataType(DataType.MultilineText)]
        public string Description { get; set; }

        public decimal Price { get; set; }

        public string AltText { get; set; }

        public int Quantity { get; set; }

        public string ImagePath { get; set; }

        public HttpPostedFileBase Image { get; set; }

        public List<ProductCategory> Category { get; set; }
    }
}

这是我的控制器

中的创建方法
[HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create(AddNewProductViewModel model)
        {
            ProductImageViewModel image = new ProductImageViewModel() { ImagePath = "/Content/ProductImages/" + model.Image.FileName, AltText = model.AltText };
            ProductImage newImage = new ProductImage() { ImagePath = image.ImagePath, AltText = image.AltText };
            entities.ProductImages.Add(newImage);
            await entities.SaveChangesAsync();
            int ImageId = newImage.ProductImageId;

            Product product = new Product()
            {
                ProductImageId = ImageId,
                ProductName = model.Name,
                ProductDescription = model.Description,
                ProductPrice = model.Price,
                Quantity = model.Quantity
                CategoryID = model.
            };

            string file = model.Image.FileName;
            string path = Server.MapPath(@"~/Content/ProductImages");
            string fullPath = path + @"\" + file;
            try
            {
                model.Image.SaveAs(path + @"\" + file);

                if (ModelState.IsValid)
                {
                    entities.Products.Add(product);
                    await entities.SaveChangesAsync();
                    return RedirectToAction("Create");
                }
            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.ToString();
            }
           //ViewBag.ProductImageId = new SelectList(entities.ProductImages, "ProductImageId", "ImagePath", product.ProductImageId);
            return View("Create");
        }

现在我想在我的视图中填充DropDownList:

<div class="form-group">
            @Html.LabelFor(model => model.Category, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.Category.Id, new SelectList(Model.Category,"Value","Text"), "- Please Select -")
                @Html.ValidationMessageFor(model => model.Category)
            </div>
        </div>

这就是我得到的错误:

  

CS0411:方法的类型参数   &#39; System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper,   System.Linq.Expressions.Expression&gt;中   System.Collections.Generic.IEnumerable,   对象)&#39;无法从使用中推断出来。尝试指定类型   明确的论点。

修改

这里是新的 AddNewProductViewModel

using AccessorizeForLess.Data;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web;

namespace AccessorizeForLess.ViewModels
{
    public class AddNewProductViewModel
    {
        public string Name { get; set; }

        [DataType(DataType.MultilineText)]
        public string Description { get; set; }

        public decimal Price { get; set; }

        public string AltText { get; set; }

        public int Quantity { get; set; }

        public string ImagePath { get; set; }

        public HttpPostedFileBase Image { get; set; }

        public ProductCategory Category { get; set; }

        public int SelectedCategoryId { get; set; }

        public List<ProductCategory> Categories { get; set; }
}
}

我在下拉列表中的更新尝试

<div class="form-group">
            @Html.LabelFor(model => model.Category, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.SelectedCategoryId,
                 new SelectList(Model.Categories, "CategoryId", "CategoryName"), "- Please Select -")
                @Html.ValidationMessageFor(model => model.Category)
            </div>
        </div>

现在我在这一行得到NullReferenceException

@Html.DropDownListFor(model => model.SelectedCategoryId,

鉴于我的代码,有人可以告诉我我在这里做错了什么,自从昨晚以来我一直在努力解决这个问题。

3 个答案:

答案 0 :(得分:7)

我解决了这个问题(感谢大家的提示)。这适用于任何可能遇到像我这样的问题的人。

我将创建方法改为:

// GET: /Products/Create
public ActionResult Create()
{
    var p = new AddNewProductViewModel();
    p.Categories = entities.ProductCategories.ToList();
    return View(p);
}

我的 AddNewProductViewModel 如下所示:

using AccessorizeForLess.Data;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web;

namespace AccessorizeForLess.ViewModels
{
    public class AddNewProductViewModel
    {
        public string Name { get; set; }

        [DataType(DataType.MultilineText)]
        public string Description { get; set; }

        public decimal Price { get; set; }

        public string AltText { get; set; }

        public int Quantity { get; set; }

        public HttpPostedFileBase Image { get; set; }

        public int SelectedCategoryId {get;set;}
        public List<ProductCategory> Categories { get; set; }
        public ProductCategory Category { get; set; }
    }
}

在我看来:

<div class="form-group">
    @Html.LabelFor(model => model.SelectedCategoryId, "Category",new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(model => model.SelectedCategoryId, new SelectList(Model.Categories, "CategoryId", "CategoryName"), "- Please Select -")
        @Html.ValidationMessageFor(model => model.SelectedCategoryId)
    </div>
</div>

感谢大家的帮助:)。

答案 1 :(得分:3)

首先,我会将您的ViewModel更改为包含SelectedCategoryId,我会将您的选项更改为Categories

如果没有看到您get的代码,我正在恭维ProductCategory,如下所示:

public class ProductCategory {
  public int Id {get;set;}
  public string Name { get;set;}
}

你的剃刀标记会变成:

<div class="form-group">
     @Html.LabelFor(model => model.Categories, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.SelectedCategoryId, 
            new SelectList(Model.Categories, "Id", "Name"), "- Please Select -")
            @Html.ValidationMessageFor(model => model.Categories)
        </div>
</div>

第一个参数是选定的catgegory,您的选项将从Categories填充。

WorkingFiddle

答案 2 :(得分:0)

使用您的控制器构建列表,然后从视图中调用列表。

<强>控制器:

public static List<SelectListItem> GetDropDown()
    {
        List<SelectListItem> ls = new List<SelectListItem>();
        lm = (call database);
        foreach (var temp in lm)
        {
            ls.Add(new SelectListItem() { Text = temp.name, Value = temp.id });
        }
        return ls;
    }

拨打下拉列表

@Html.DropDownListFor(x => x.Field, PathToController.GetDropDown())