我需要做的是 - > 在2个不同模型的视图上绑定2 DropDownListFor,我知道无法实现,因为只能调用一个模型单一视图。
初始要求
@ Html.DropDownListFor(M => M.MobileList,new SelectList(Model.MobileList," Value"," Text"))
@ Html.DropDownListFor(M => M.CountryList,new SelectList(Model.CountryList," Value"," Text"))
我做了什么
使用
将其中一个下拉列表绑定@ Html.DropDownListFor(M => M.MobileList,new SelectList(Model.MobileList," Value"," Text"))
对于其他使用过的ViewBag。
@Html.DropDownList("Countrylist", (IEnumerable<SelectListItem>)ViewBag.Countrylist, new { id = "CountryId", @class = "form-control", @multiple = "multiple" })
但我需要使用@ Html.DropDownListFor razor代码创建下拉列表。
答案 0 :(得分: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" })
答案 1 :(得分: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"))
答案 2 :(得分:0)
public class MainModel{
public int CountryId {get;set;}
public int MobileValue {get;set;}
public Tuple<List<MobileList>,List<CountryList>> {get;set;}
}
如果您只有一个型号,请将元组用于多个列表。