MVC DropDownListFor

216 views Asked by At

I am new using MVC approach. How to using the DropDownListfor in the MVC? I need get the list from my master table and show the option into the Business Premise in the Business Profile object. This is my ViewModel

 public class SMEAppViewModel 

{        
    public WP2PBusinessProfile BuisinessProfile  { get; set; }        
    public IEnumerable<WP2PMasterDropDownList> MasterList { get; set; }       

}

In my controller, I already initialize the MasterList to the List

 var _MasterList = _context.WP2PMasterDropDownList.ToList();

And in my view, I able to display all the option in the List by using the following code

 @foreach (var karim in Model.MasterList.Where(c => c.Variable == "BusinessPremise"))
                    {

                        @Html.DisplayFor(modelitem => karim.Value) <br>                            

                    }

However, I using the following dropdownlistfor in my view, but my DropDownlistfor is not able to show my drop down option in my view.

 @Html.DropDownListFor(m => m.BuisinessProfile.BusinessPremise, new SelectList(Model.MasterList, "Id", "Value"), "Select value")
                                    @Html.LabelFor(m => m.BuisinessProfile.BusinessPremise, new { @class = "form-control" })

would anyone tell me any wrong in my code?

Thanks

2

There are 2 answers

0
Karnav Modi On

If you just want to display text options in dropdown then try to use list of 'selectlistitem' and then fill out this list with foreach loop like

List<SelectListItem> ls = new List<SelectListItem>();
foreach (var temp in yourlist)
{
   ls.Add(new SelectListItem() 
   { Text = temp.textfield, Value = Convert.ToString(temp.valuefield) });
}

after this add this list to your view field (MasterList for your case but change type to List<SelectListItem>) this will display the dropdown list and to get selected value you can use javascript and jquery with ajax call for further process.

var dropdownvalue = $("#AccountGroupID option:selected").val();
var dropdowntext = $("#AccountGroupID option:selected").text();

this will give you value and text for selected item.

In view to display dropdownlist you can try it like this.

@Html.DropDownListFor(model => model.BuisinessProfile, new SelectList(Model.MasterList, "Value", "Text"), "-- Select --", htmlAttributes: new { @class = "form-control", id = "dropdown"})
0
Thisara Subath On

Try this in your view

@Html.DropDownListFor(m => m.Entity, new Project.Models.My_Class().My_Method, new { @class = "form-control" })

You cant get data from your DropDownListFor.

In the My_Method , You can use SelectList