2016-09-09 60 views
-2

我正在尋找從數據來自數據庫的viewmodel填充下拉列表。以下是對我的項目看起來像手短:asp.net mvc從視圖模型下拉列表

型號

public partial class Model1 
{ 
    public string FirstName { get; set; } 

    public string LastName { get; set; } 
} 

模型2 - 這將是填充下拉列表

public partial class Model2 
{ 
    public string typeID { get; set; } 

    public string typeValue { get; set; } 
} 

這兩款車型則連接的信息到ViewModel。

視圖模型

public class viewModel 
{ 
    public Model1 Model1s { get; set; } 

    public Model2 Model2s { get; set; } 
} 

我無法創建使用視圖模型在這一點上下拉列表中。我已經梳理了這個網站上的大約50個例子,但我無法讓我的工作。我知道該視圖包含以下內容:

@Html.DropDownListFor(m => m.MarketingCampaign , new SelectList(Model.MarketingCampaignType, "CampaignTypeTitle", "CampaignTypeId"), new { id = "yourElementIdIfAny", @class = "yourClassNameIfAny" }) 

將需要。我也試圖直接輸入的值和文本到模型中的一個領域,所以我可以很容易地從被傳遞迴控制器,而不是使用此方法的這個模型中提取信息:

ViewBag.DropDownList = dbContext.Model2.ToList(); 

和檢索信息從經過形式背部和使用:

string value = form["DropDownList"].ToString() 
+1

http://stackoverflow.com/questions/9882700/how-do-i-create-a-view-model-for-a-人口-下拉列表,在-ASP淨MVC-3 – mmcrae

回答

1

我創建實例和上傳在Github上

Source code

public ActionResult Index() 
    { 
     //IsName >> Is name DropDownList 
     //typeID >> Is data value 
     //typeValue >> Is data text 
     ViewBag.IsName = new SelectList(_dbContext.Model2.ToList(), "typeID", "typeValue"); 
     return View(); 
    } 
    public ActionResult ByViewModel() 
    { 
     List<ViewModel> items = _dbContext.Model2.Select(m => new ViewModel() 
     { 
      typeID = m.typeID, 
      typeValue = m.typeValue 
     }).ToList(); 

     //IsName >> Is name DropDownList 
     //typeID >> Is data value 
     //typeValue >> Is data text 
     ViewBag.IsName = new SelectList(items, "typeID", "typeValue"); 
     return View(); 
    } 

@ Html.DropDownList( 「IsName」)