Asp.net mvc 4 mvc4中“编辑”视图中的“不工作”下拉列表
我无法从mvc4中的下拉列表中获取正确的值。我的编辑视图代码是Asp.net mvc 4 mvc4中“编辑”视图中的“不工作”下拉列表,asp.net-mvc-4,Asp.net Mvc 4,我无法从mvc4中的下拉列表中获取正确的值。我的编辑视图代码是 @Html.DropDownList("IDCountry", (IEnumerable<SelectListItem>)ViewBag.IDCountry, new { @class = "span6" }) 请解决我的问题。您不应该使用相同的值(IDCountry)作为下拉列表的第一个和第二个参数。第一个参数表示要绑定下拉列表的值,而第二个参数表示可用值。因此: @Html.DropDownList(
@Html.DropDownList("IDCountry", (IEnumerable<SelectListItem>)ViewBag.IDCountry,
new { @class = "span6" })
请解决我的问题。您不应该使用相同的值(
IDCountry
)作为下拉列表的第一个和第二个参数。第一个参数表示要绑定下拉列表的值,而第二个参数表示可用值。因此:
@Html.DropDownList(
"SelectedCountryID",
(IEnumerable)ViewBag.IDCountry,
new { @class = "span6" }
)
为了避免所有这些与下拉列表的混淆,我建议您使用视图模型:
public class MyViewModel
{
public string SelectedCountryID { get; set; }
public IEnumerable<SelectListItem> Countries { get; set; }
}
最后,在您的视图中使用强类型帮助器:
@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>
}
@model MyViewModel
@使用(Html.BeginForm())
{
@LabelFor(x=>x.SelectedCountryID)
@Html.DropDownListFor(
x=>x.SelectedCountryID,
示范国,
新建{@class=“span6”}
)
好啊
}
看到你停止使用ViewBag并在应用程序中完全删除它的所有痕迹的瞬间,一切都变得非常清晰了吗?代码不是我写的。现在不可能改变你的方式,那么有没有办法将CSS应用于下面类型的代码@Html.DropDownList(“IDCountry”,String.empty)是的,你可以使用我答案第一部分中的示例。@Anilreddy同意Darin。。。你可以重写任何东西,这应该是吉文给你的所有例子都很难做到的。我测试了它们,它们很有效。
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>
}