4

我的视图中有一个静态下拉列表

<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
}

控制器获取操作方法

[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 回答