在编辑器模板中设置selectlist的默认选择值

问题描述 投票:3回答:3

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

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"
    )
%>
asp.net-mvc model drop-down-menu selectlist mvc-editor-templates
3个回答
10
投票

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

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

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


1
投票

将其添加到您的控制器:

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

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

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

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" })
© www.soinside.com 2019 - 2024. All rights reserved.