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 つの方法です


ステップ 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 に答える