2016-11-27 65 views
0

我有一個下拉列表正在通過ViewBag變量填充,我想知道如何使用id值設置此列表的選定索引。Html.DropdownList與選定的值

這是我創作的ViewBag變量,記下編號,這就是我要用來設置在列表中的默認選擇的項目是什麼:

var events = db.Events.Select(e => new 
      { 
       id = e.EventID, 
       Name = e.EventTitle 

      }).OrderBy(e => e.Name).ToList(); 
      ViewBag.EventsList = new MultiSelectList(events, "id", "Name"); 

這是在查看下拉:

@Html.DropDownList("id", (MultiSelectList)ViewBag.EventsList, new { @class = "form-control", id = "lstTopFeaturedEvent" }) 

反正是有,我可以使用id屬性設置控制器設置的默認選擇值?

+1

設置在將模型傳遞給視圖之前,您可以在GET方法中使用屬性'id'的值(並且您可以簡單地使用ViewBag.EventsList = new SelectList(db.Events,「EventID」,「EventTitle」);') –

回答

1

您應該使用視圖模型,並忘記ViewBag認爲它好像它不存在。你會看到事情變得更容易。所以定義視圖模式:

public class MyViewModel 
{ 
    public int SelectedCategoryId { get; set; } 
    public IEnumerable<SelectListItem> Categories { get; set; } 
} 

,然後填充這個視圖控制器模型:

public ActionResult NewsEdit(int ID, dms_New dsn) 
{ 
    var dsn = (from a in dc.dms_News where a.NewsID == ID select a).FirstOrDefault(); 
    var categories = (from b in dc.dms_NewsCategories select b).ToList(); 

    var model = new MyViewModel 
    { 
     SelectedCategoryId = dsn.NewsCategoriesID, 
     Categories = categories.Select(x => new SelectListItem 
     { 
      Value = x.NewsCategoriesID.ToString(), 
      Text = x.NewsCategoriesName 
     }) 
    }; 
    return View(model); 
} 

終於在您的視圖中使用強類型DropDownListFor幫手:

@model MyViewModel 

@Html.DropDownListFor(
    x => x.SelectedCategoryId, 
    Model.Categories 
)