4

ビューに 1 つの静的ドロップダウン リストがあります

<select>
 <option value="volvo">Volvo</option>
 <option value="saab">Saab</option>
 <option value="mercedes">Mercedes</option>
 <option value="audi">Audi</option>
</select>

このドロップダウンリストをモデルにバインドして、選択した値を送信すると、コントローラーのモデルからその値が取得されるようにします。

また、モデルのデータに従って、ドロップダウンでオプションを選択したいと考えています。

4

3 に答える 3

6

静的ドロップダウンリストのリストアイテムを作成し、それをドロップダウンリストに渡して、ビューモデルにバインドしました。

 @{
   var listItems = new List<ListItem> {new ListItem {Text = "Single", Value = "Single"}, new ListItem {Text = "Married", Value = "Married"}, new ListItem {Text = "Divorse", Value = "Divorse"}};
   }
 @Html.DropDownListFor(model => model.EmployeeDetail.MaritalStatus, new SelectList(listItems),"-- Select Status --")

モデルからの値を表示し、データを送信するときにドロップダウンリストの値をモデルに保存するので、私にとっては完璧に機能します。

于 2013-01-31T09:36:53.873 に答える
3

HTML でドロップダウン リストを作成する代わりに、サービス/コントローラーで作成し、モデルに追加します。

ビューモデル:

public class YourViewModel
{
    public string SelectedCarManufacturer { get; set; }

    public Dictionary<string, string> CarManufaturers { get; set; }

    // your other model properties
}

コントローラ get アクション メソッド

[HttpGet]
public ActionResult SomeAction()
{
    var model = new YourViewModel
    {
        SelectedCarManufacturer = null, // you could get this value from your repository if you need an initial value
        CarManufaturers = new Dictionary<string, string>
        {
            { "volvo", "Volvo" },
            { "saab", "Saab" },
            { "audi", "Audi" },
            /// etc.
        }
    };

    return this.View(model);
}

ビューで、ハードコードされたドロップダウン リストを次のように置き換えます。

@Html.DropDownListFor(m => m.SelectedCarManufacturer , new SelectList(Model.CarManufaturers , "Key", "Value"), "Select a manufacturer...")

コントローラ ポスト アクション メソッド

[HttpPost]
public ActionResult SomeSaveAction(YourViewModel model)
{
    // do something with the model...
    // model.SelectedCarManufacturer 
}

また

[HttpPost]
public ActionResult SomeSaveAction()
{
    var model = someService.BuildYourViewModel()
    this.TryUpdateModel(model);

    // do something with the model...
    someService.SaveYourViewModel(model);
}

これが役立つことを願っています...

于 2013-01-30T12:58:32.853 に答える
0

コントローラーで

List<SelectListItem> items = new List<SelectListItem>();

     items.Add(new SelectListItem { Text = "Volvo", Value = "volvo"});

     items.Add(new SelectListItem { Text = "Saab", Value = "saab" });

     items.Add(new SelectListItem { Text = "Mercedes", Value = "mercedes" });

     items.Add(new SelectListItem { Text = "Audi", Value = "audi" });

オンビュー

Html.DropDownListFor(Model.items)
于 2013-01-30T12:42:13.683 に答える