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

Aiv*_*ler 3 asp.net-mvc model selectlist mvc-editor-templates drop-down-menu

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

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);
}
Run Code Online (Sandbox Code Playgroud)

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

<%: Html.DropDownListFor(model => model.CountryId, Model.CountryList ,"Select Country") %>
Run Code Online (Sandbox Code Playgroud)

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

所以,我将当前视图更改为:

 <%: Html.EditorFor(model => model.CountryId,new { countries = Model.CountryList}) %>
Run Code Online (Sandbox Code Playgroud)

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

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

Aiv*_*ler 12

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

CountryList = new SelectList(countryList, "CountryId", "CountryName",52 /*Default Country Id*/)
Run Code Online (Sandbox Code Playgroud)

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