Setting the default value of the selected list in the editor template

I have this code to set the default value for 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 in my opinion and it works well for the selected value of country 52:

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

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

So, I am changing my current view to the following:

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

Then I create my editor template as follows:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.Int64?>" %>
<%= Html.DropDownList(
        String.Empty /* */, 
        (SelectList)ViewData["countries"], 
        "Select Country"
    )
%>
+3
source share
3 answers

I solved this by replacing the code in my controller with:

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

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

+10
source

:

ViewData["CountryList"] = new SelectList(_countryRepository.GetAllCountry(), 52);

:

@Html.DropDownList("Countries", ViewData["CountryList"] as SelectList)
+1

Different ways to archive this, this is one way


Step 1: Set the value that you should select by default. here I went 0 or 2

    ViewBag.AssessmentfrezeId = IsUserHavefreeAssessment == false ? 2 : 0;

Step 2: Add the selected value to Cshtml as shown below.

 @Html.DropDownListFor(m => m.TestID, new SelectList(Model.Slots, "Id", "TimeSlot", @ViewBag.AssessmentfrezeId), "--Select--", new { @class = "form-control" })
0
source

Source: https://habr.com/ru/post/1781176/


All Articles