1
votes

What I need is to do is--> Bind 2 DropDownListFor on a view with 2 different model, which I know can't be achieved as only one model can be called on a single view.

Initial Requirement

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

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

What I did

Binded one of the dropdown using

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

For the Other Used ViewBag.

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

But I need to create both the dropdown using @Html.DropDownListFor razor code.

3
Did you consider using a "Tuple" like this Tuple<MobileListModel,CountryListModel> as model for the view?User3250

3 Answers

0
votes

Example:

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;}
}

In view

@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" }))

You can also use

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

You can create a parent model as below and using it in your view:

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

and then in your view:

@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
votes
    public class MainModel{
  public int CountryId {get;set;}
  public int MobileValue {get;set;}
  public Tuple<List<MobileList>,List<CountryList>>  {get;set;}
}

Please use the tuple for multiple list if you have only one model.