2011-08-28 155 views
0

我必須將所選項目的ID保存到數據庫中。但是,當我從下拉列表中選擇一個項目時,我總是會得到一個空值。在下拉列表中獲取所選項目的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

Html.DropDownList的第一個參數是HTML標識。

添加CategoryId到您的視圖模型,改變你的下拉列表:

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

或者,這可能與當前的代碼工作(而不是測試):

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

在我當前的代碼有沒有什麼叫「Category_ID」!! – kandroid

+0

Asp.Net MVC將Category.ID轉換爲Category_ID ...試試看 – Martin

+0

Nop ..「Category_ID」不起作用。 – kandroid

相關問題