在下拉列表中获取所选项目的ID

时间:2011-08-28 22:04:30

标签: asp.net-mvc model-view-controller drop-down-menu

我必须将所选项目的ID保存到数据库中。但是,当我从下拉列表中选择一个项目时,我总是得到一个空值。

这是一些代码: 控制器:

public ActionResult Create()
    {
        SelectList CategoryList = new SelectList(dc.Category.ToList(), "ID", "CategoryName");
        ViewData["Categories"] = CategoryList;
        ViewData.Model = new AdvertModel();
        return View();
    }

查看:

<%:Html.DropDownList("Categories", ViewData["Categories"] as SelectList, new { @class = "dropdown" })%>

MODEL:AdvertModel

public class AdvertModel
{
    public Int32 ID { get; set; }

    [Required(AllowEmptyStrings=false,ErrorMessage="Please enter the title of your Ad.")]
    [Display(Name="Title")]
    public string Title { get; set; }

    [Required(AllowEmptyStrings=false,ErrorMessage="Please enter a description of your Ad.")]
    [Display(Name = "Details")]
    public string Details { get; set; }

    [Required(AllowEmptyStrings=false,ErrorMessage="Please enter when your Ad. will be publish")]
    [Display(Name = "Publish date")]
    [DataType(DataType.Date)]
    public DateTime PubDate { get; set; }

    [Required]
    public DateTime EntryDate { get; set; }

    public bool AdStatus { get; set; }

    [Required]
    [Display(Name = "Category")]
    public Category Category { get; set; }

}

现在我想获取所选项目的ID:

public ActionResult Create(AdvertModel ad)
    {
        Advert nAD = new Advert();
        nAD.Title = ad.Title;
        nAD.Message = ad.Details;
        nAD.PublishDate = ad.PubDate;

        nAD.Category = ad.Category.ID;// here I always get null. 

        dc.Advert.AddObject(nAD);
        dc.SaveChanges();

        return View(ad);
    }

知道我哪里做错了吗?

1 个答案:

答案 0 :(得分:2)

Html.DropDownList的第一个参数是HTML Id。

向您的ViewModel添加CategoryId并将您的下拉列表更改为:

<%:Html.DropDownList("CategoryId", ViewData["Categories"] as SelectList, new { @class = "dropdown" })%>

或者这可能适用于您当前的代码(但未经过测试):

<%:Html.DropDownList("Category_ID", ViewData["Categories"] as SelectList, new { @class = "dropdown" })%>