Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to set an item in dropdown list as default in MVC
in below code


Controller.cs
C#
var usrModel = new UserRegisterModel();
            Country curid = snwe.Countries.Where(a => a.Country1 == "India").FirstOrDefault(); 
            usrModel.Countries = snwe.Countries.AsEnumerable().Select(C => new SelectListItem
            { 
                Text = C.Country1,
                Value = C.CountryID.ToString().Trim(),
               Selected = C.CountryID == curid.CountryID?true:false
                
            });

View.cshtml
HTML
<li>
    <div class="eq-box">
        <label>@(LocalizationProvider.Current.CountryLabel)*
        <span class="validate-msg">@Html.ValidationMessageFor(m => m.CountryId)</span></label>
        <div class="eq-box-field">
        @Html.DropDownListFor(m => m.CountryId, Model.Countries,  new { @class = "dropdown" })
        </div>
    </div>
</li>
Posted
Updated 15-Oct-15 0:08am
v2
Comments
Krunal Rohit 15-Oct-15 6:10am    
Looks good.
Any error ?

-KR
Nathan Minier 15-Oct-15 7:52am    
You've got a bug waiting to happen. Change:

Selected = (curid != null && C.CountryID == curid.CountryID) ?true:false

1 solution

You can create a separate method to bind country dropdown-
C#
public static SelectList GetCountries(int selected = 0)
       {
           return new SelectList(Repository.Instance.All<country>(), "Id", "Name", selected);
       }</country>


HTML
@Html.DropDownListFor(x=>x.CountryId,GetCountries(x.CountryId),"[Select]")


The method return type is SelectList so you don't need to worry about select item or any other thing.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900