Setting default selected value of selectlist inside an editor template
Asked Answered
G

3

6

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"
    )
%>
Geraldo answered 20/12, 2010 at 3:7 Comment(0)
G
15

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.

Geraldo answered 20/12, 2010 at 3:32 Comment(0)
G
1

Add this to your Controller:

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

Then, on the View page, call the dropdown as follows:

@Html.DropDownList("Countries", ViewData["CountryList"] as SelectList)
Geomancy answered 10/3, 2011 at 17:18 Comment(0)
D
0

Different ways to Archive this, This is One way


Step 1: Set the value you nee to be default selected. here I have passed 0 or 2

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

Step 2: Go to the Cshtml added the selected value like below.

 @Html.DropDownListFor(m => m.TestID, new SelectList(Model.Slots, "Id", "TimeSlot", @ViewBag.AssessmentfrezeId), "--Select--", new { @class = "form-control" })
Denisse answered 29/4, 2019 at 6:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.