0

我想从两个 DropDowns 访问 Selected Keys,然后以 Keys 作为参数调用控制器操作。

在我的 MVC 视图中,我有以下代码:

@model Test.Models.LoginViewModel
<p>
    Database @Html.DropDownListFor(x => x.SelectedDatabase, Model.DatabaseList, "-- Select an Item --", new {@id="databaseDD", @name="databaseDD"})
</p>
<p>
    Language @Html.DropDownListFor(x => x.SelectedLanguage, Model.LanguageList, "-- Select an Item --", new {@id="languageDD", @name="languageDD"})
</p>
<p>
    @using (Html.BeginForm("LoginToService", "Home", new { databaseKey = Model.SelectedDatabase, languageKey = Model.SelectedLanguage }, FormMethod.Post, new { target = "_self" }))
    {
        <input id="login" type="submit" name="login" value="Login" />
    }
</p>

问题是,当下拉选择更改时,未设置属性 Model.SelectedDatabase 和 Model.SelectedLanguage。如何访问 Selected Keys 并将它们用作参数?

4

1 回答 1

0

在您的控制器中,您应该使用预定义的类,如下所示:

 public class DropDownItem
    {

        public int Key { get; set; }
        public string Value{ get; set; }
    }

使用后端方法将所需字段映射到 DropDownItem ,例如:

    public SelectList FooListUsed()
    {
     List<DropDownItem> result =  from item in ListOfDataBaseTableElements
               select new DropDownItem{
                    Key = item.id,
                    Value = item.name
                     }
     result.Insert(0, new DropDownItem{ Key = 0, Value = "Select All" });
     return new SelectList(result, "Key", "Value"); //this mapping will take care of your selected value issue

通过 Viewbag 或 Model 将查询结果传递给视图,让我们在本例中使用 viewbag:ViewBag.FooList=FooListUsed();

最后一步......使用你的下拉列表:

@Html.DropDownListFor(model => model.SelectedDatabase,(IEnumerable<SelectListItem>)ViewBag.FooList)
于 2013-03-05T14:15:37.697 回答