5

我有这段代码来设置我的选择列表的默认值:

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);
}

我有这个观点,这很好地将选定的国家/地区值设置为 52:

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

但是,当我为此创建编辑器模板时,未选择国家/地区的默认值

因此,我将当前的视图更改为:

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

然后我像这样创建我的编辑器模板:

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

3 回答 3

13

我通过将控制器中的代码替换为:

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

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

于 2010-12-20T03:32:51.180 回答
1

将此添加到您的控制器:

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

然后,在“查看”页面上,按如下方式调用下拉菜单:

@Html.DropDownList("Countries", ViewData["CountryList"] as SelectList)
于 2011-03-10T17:18:25.843 回答
0

存档的不同方法,这是一种方法


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

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

第 2 步:转到 Cshtml 添加所选值,如下所示。

 @Html.DropDownListFor(m => m.TestID, new SelectList(Model.Slots, "Id", "TimeSlot", @ViewBag.AssessmentfrezeId), "--Select--", new { @class = "form-control" })
于 2019-04-29T06:46:52.250 回答