asp.net-mvc 在编辑器模板中设置选择列表的默认选择值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4486577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:39:24  来源:igfitidea点击:

Setting default selected value of selectlist inside an editor template

asp.net-mvcmodeldrop-down-menuselectlistmvc-editor-templates

提问by Aivan Monceller

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:

我认为这很有效,将选定的国家/地区值设置为 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"
    )
%>

回答by Aivan Monceller

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.

如果您有更好的解决方案,请告诉我。我会改变接受的答案。

回答by WEFX

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)

回答by Hari Lakkakula

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

步骤1:设置您需要默认选择的值。在这里我已经通过了 0 或 2

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

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

第 2 步:转到 Cshtml 添加如下选定的值。

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