1

SelectList で選択した ID (CountryId) からテキスト値 (CountryName) を表示するにはどうすればよいですか? SelectList は、詳細ビュー テンプレートに送信されるビュー モデルに含まれています。フィールドには現在 CountryID が表示されています。国名が欲しい。

見る

<div class="display-field">@Model.Dinner.CountryID</div>

コントローラ

public ActionResult Details(int id)
    {
        Dinner dinner = dinnerRepository.GetDinner(id);
        DinnerFormViewModel model = new DinnerFormViewModel(dinner);
        if (dinner == null)   
            return View("NotFound");       
        else           
            return View("Details", model);
    }

ビューモデル

public class DinnerFormViewModel
{
    public Dinner Dinner { get; private set; }
    public SelectList CountriesList { get; private set; }

    public DinnerFormViewModel(Dinner dinner)
    {
        Dinner = dinner;

        var items = new List<Country>() {
                new Country() { 
                    CountryID = 1,
                    CountryName = "England"
                },
                new Country() { 
                    CountryID = 2,
                    CountryName = "Ireland"
                },
                new Country() { 
                    CountryID = 3,
                    CountryName = "Scotland"
                },
                new Country() { 
                    CountryID = 3,
                    CountryName = "Wales"
                }
            };

        CountriesList = new SelectList(items, "CountryID", "CountryName", 2);
    }
}

ここでも、CountryName 値をラベルに表示するだけです。それか何かを編集したくありません。LINQ式?

4

2 に答える 2

2

これはうまくいきます

<div class="display-label">Country</div>
<div class="display-field">@Html.Encode(Model.CountriesList.SingleOrDefault(c => int.Parse(c.Value) == Model.Dinner.CountryID).Text)</div>

関連記事のおかげで。

于 2011-01-31T14:28:12.420 に答える
1

検索に役立つ新しいクラスを作成します。私のコード例では、クラスは「BusinessResources」です。そのクラスでは、国について以下に示すような各ルックアップのメソッドを作成します。辞書は、達成しようとしていることに最適です。

public static Dictionary<string, string> GetCountryList()
        {
            Dictionary<string, string> country = new Dictionary<string, string>();

            Capture2Entities db = new Capture2Entities();
            country = db.CountryLists.Where(x => x.IsDisabled == false)
                                 .OrderBy(x => x.CountryName)
                                 .Select(x => new { x.ID_Country, x.CountryName })
                                 .ToDictionary(key => key.ID_Country.ToString(), val => val.CountryName);
            return country;
        }

ビューは次のようになります

<div class="display-label">@Html.LabelFor(model => model.ID_Country)</div>
<div class="display-field">@Html.DropDownListFor(model => model.ID_Country, new SelectList(BusinessResources.GetCountryList(),"Key","Value"))</div>
于 2013-07-31T19:10:41.517 に答える