2017-05-04 55 views
1

我需要做的是 - >綁定2 DropDownListFor在2個不同模型的視圖,我知道不能實現,因爲只有一個模型可以被調用在一個單一的觀點。如何填充2 DropDownListFor爲強類型模型

初始需求

@ Html.DropDownListFor(M => M.MobileList,新的SelectList(Model.MobileList, 「值」, 「文本」))

@ Html.DropDownListFor(M => M.CountryList,新的SelectList(Model.CountryList, 「價值」, 「文本」))

我做什麼

綁定下降的一個下使用

@ Html.DropDownListFor(M => M.MobileList,新的SelectList(Model.MobileList, 「價值」, 「文本」))

爲其他二手ViewBag。

@Html.DropDownList("Countrylist", (IEnumerable<SelectListItem>)ViewBag.Countrylist, new { id = "CountryId", @class = "form-control", @multiple = "multiple" }) 

但是我需要創建兩個使用@ Html.DropDownListFor剃刀碼下拉。

+1

您是否考慮使用像這個Tuple 這樣的「Tuple」作爲視圖的模型? – User3250

回答

0

例子:

public class Model1{ 
    public int MobileId {get;set;} 
    public Model2 Model2{get;set;} 
    public List<SelectListItem> MobileList {get;set;} 
} 

public class Model2{ 
    public int CountryId {get;set;} 
    public List<SelectListItem> CountryList {get;set;} 
} 

鑑於

@model Model1 

    @Html.DropDownListFor(M => M.MobileId,Model.MobileList, new { @class ="form-control" })) 

    @Html.DropDownListFor(M => M.Model2.CountryId,Model.Model2.CountryList, new { @class ="form-control" })) 

您還可以使用

@Html.DropDownListFor(M => M.Model2.CountryId, new SelectList((IEnumerable)ViewBag.Countrylist,"Value", "Text"), new { id = "CountryId", @class = "form-control", @multiple = "multiple" }) 
+0

我有2個獨立的模型。 M => M.CountryList在MobileList型號上不可用 –

+0

您的意思是2個獨立的型號? 'MobileList'和'CountryList'存在於不同的模型中? – Ashiquzzaman

+0

是的,這些是2個獨立的模型 –

0

您可以按下面創建一個父模型,並在您的視圖中使用它:

public class MainModel{ 
    public int CountryId {get;set;} 
    public int MobileValue {get;set;} 
    public List<MobileList> {get;set;} 
    public List<CountryList> {get;set;} 
} 

,然後在您的視圖:

@model MainModel 

@Html.DropDownListFor(M => M.MobileValue, new SelectList(Model.MobileList,"Value", "Text")) 

@Html.DropDownListFor(M => M.CountryId, new SelectList(Model.CountryList,"Value", "Text")) 
+0

只是想檢查我們是否使用ViewBag,而使用@ Html.DropDownListFor作爲它的第一個參數是lamda表達式。 –

+0

@RohitKumar不能期待模型屬性作爲第一個參數 – User3250

+0

有什麼辦法可以擴展這個方法嗎?並避免使用MainModel? –

0
public class MainModel{ 
    public int CountryId {get;set;} 
    public int MobileValue {get;set;} 
    public Tuple<List<MobileList>,List<CountryList>> {get;set;} 
} 

請使用多個列表中的元組,如果你只有一個模型。