在mvc4 razor的编辑视图中没有工作的下拉列表

时间:2013-06-11 12:43:23

标签: asp.net-mvc-4

无法从mvc4中的下拉菜单中获取正确的值。我的编辑视图代码是

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

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

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

请解决我的问题。

1 个答案:

答案 0 :(得分:2)

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

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

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

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并在你的应用程序中删除它的所有痕迹,一切都变得清晰了吗?