-3

我无法从 mvc4 的下拉列表中获得正确的值。我的编辑视图代码是

@Html.DropDownList("IDCountry", (IEnumerable<SelectListItem>)ViewBag.IDCountry, 
    new { @class = "span6" })

如果我使用下面的代码能够获得正确的值但无法为下拉列表应用样式

@Html.DropDownList("IDCountry",String.empty)

请解决我的问题。

4

1 回答 1

2

您不应使用与IDCountry下拉列表的第一个和第二个参数相同的值 ( )。第一个参数表示要将下拉列表绑定到的值,而第二个参数表示可用值。所以:

@Html.DropDownList(
    "SelectedCountryID", 
    (IEnumerable)ViewBag.IDCountry, 
    new { @class = "span6" }
)

为了避免所有这些与下拉菜单的混淆,我建议您使用视图模型:

public class MyViewModel
{
    public string SelectedCountryID { get; set; }
    public IEnumerable<SelectListItem> Countries { get; set; }
}

然后您的控制器操作将填充并将此视图模型传递给视图:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel();
        // preselected an element with Value = "2"
        model.SelectedCountryID = "2";

        // obviously those values could come from a database or something
        model.Countries = new[]
        {
            new SelectListItem { Value = "1", Text = "Country 1" },
            new SelectListItem { Value = "2", Text = "Country 2" },
            new SelectListItem { Value = "3", Text = "Country 3" },
            new SelectListItem { Value = "4", Text = "Country 4" },
        };

        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return Content("Thanks for selecting country ID: " + model.SelectedCountryID);
    }
}

最后在您看来,使用强类型帮助器:

@model MyViewModel

@using (Html.BeginForm())
{
    <div>
        @Html.LabelFor(x => x.SelectedCountryID)
        @Html.DropDownListFor(
            x => x.SelectedCountryID, 
            Model.Countries, 
            new { @class = "span6" }
        )
    </div>

    <button type="submit">OK</button>
}

看看您停止使用 ViewBag 并在您的应用程序中从其中完全删除所有痕迹的那一刻,一切都变得一清二楚了吗?

于 2013-06-11T13:10:44.387 回答