2017-05-04 6 views
1

私が必要とするのは - >バインド2 DropDownListForは2つの異なるモデルを持つビューで、1つのモデルしか呼び出せないので実現できません単一のビューでHtml.DropDownListFor @ Html.DropDownListFor @設定する方法2 DropDownListFor for Strongly Typedモデル

初期要件

(M => M.MobileList、新しいSelectListの(Model.MobileList、 "値"、 "テキスト"))

(M => M.CountryList、新しいSelectListの(Model.CountryList、 "バリュー"、 "テキスト")私は

ドロップの1バインドさやった)

その他の使用済みViewBagについてはHtml.DropDownListFor @

を使用してダウン(M => M.MobileList、新しいSelectListの(Model.MobileList、 "値"、 "テキスト"))

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

は、しかし、私は、@ Html.DropDownListForかみそりのコードを使用して、ドロップダウンの両方を作成する必要があります。

+1

このタプルのような「タプル」をビューのモデルとして使用することを検討しましたか? – 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

@ Html.DropDownListForを使用してViewBagを使用できないかどうかを確認するには、最初のパラメータとして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;} 
} 

一つだけのモデルを持っている場合は、複数のリストのためのタプルを使用してください。

関連する問題