Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting default selected value of selectlist inside an editor template

I have this code to set the default value of my select list:

public ActionResult Register()
{
    IList<Country> countryList = _countryRepository.GetAllCountry();

    var registerViewModel = new RegisterViewModel
    {
        CountryId = 52,
        CountryList = new SelectList(countryList, "CountryId", "CountryName", "Select Country")
    };

    return View(registerViewModel);
}

I have this on my view and this works well sets the selected country value to 52:

<%: Html.DropDownListFor(model => model.CountryId, Model.CountryList ,"Select Country") %>

However when I create an editor template for this, the default value for country is not selected

So, I change my current view to this:

 <%: Html.EditorFor(model => model.CountryId,new { countries = Model.CountryList}) %>

Then I create my editor template like this:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.Int64?>" %>
<%= Html.DropDownList(
        String.Empty /* */, 
        (SelectList)ViewData["countries"], 
        "Select Country"
    )
%>
like image 801
Aivan Monceller Avatar asked Dec 20 '10 03:12

Aivan Monceller


1 Answers

I have solved this by replacing the code in my controller to :

CountryList = new SelectList(countryList, "CountryId", "CountryName",52 /*Default Country Id*/)

If you have better solutions, please let me know. I will change accepted answer.

like image 122
Aivan Monceller Avatar answered Oct 09 '22 09:10

Aivan Monceller