ASP.NET MVC Dropdownlist在发布后在浏览器中保留所选值
我在我的 aspx 页面中构建了一个下拉列表,如下所示,
<%= Html.DropDownList("SelectedRole", new SelectList((IEnumerable)Model.roles, "RoleId", "RoleName", Model.SelectedRole), "")%>
它对于第一个 Get 工作正常,并且选择了第一个默认值;然后我从下拉列表中选择项目并提交表单。
控制器正确绑定值,
public ActionResult About([Bind] Roles r)
{
//r.SelectedRole = the selected value in the page.
//Roles r = new Roles();
r.roles = new List<Role>();
r.roles.Add(new Role(1, "one"));
r.roles.Add(new Role(2, "two"));
r.roles.Add(new Role(3, "three"));
r.roles.Add(new Role(4, "four"));
r.SelectedRole = null;
return View(r)
}
然后我取消所选项目并返回我的视图,但仍然选择了先前选择的项目(尽管我确实取消了它)
如果我做错了什么或者这是 MVC 中的错误,有什么想法吗?
我正在使用 ASP.NET MVC 1
谢谢
I build a drop down list in my aspx page as following
<%= Html.DropDownList("SelectedRole", new SelectList((IEnumerable)Model.roles, "RoleId", "RoleName", Model.SelectedRole), "")%>
it works fine for first Get and the first default value is selected; then I select item from the drop down list and submit the form.
the controller bind the values correctly,
public ActionResult About([Bind] Roles r)
{
//r.SelectedRole = the selected value in the page.
//Roles r = new Roles();
r.roles = new List<Role>();
r.roles.Add(new Role(1, "one"));
r.roles.Add(new Role(2, "two"));
r.roles.Add(new Role(3, "three"));
r.roles.Add(new Role(4, "four"));
r.SelectedRole = null;
return View(r)
}
Then I nullify the selected item and return my view, but still the previous selected Item is selected (although I did nullify it)
Any Idea if I am doing something wrong or it is a bug in MVC?
I am using ASP.NET MVC 1
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是所有 html 帮助程序的正常行为:它们将查看 POSTed 值来执行绑定。这意味着如果您使用标准助手,您无法更改控制器操作中的值并期望它反映在视图上。如果 POST 中有一个值
SelectedRole
,那么它将始终使用该值,并且下拉列表的最后一个参数将被完全忽略。您可以编写自己的帮助程序来实现此目的或在 POST 之后重定向。
This is the normal behavior of all html helpers: they will look at the POSTed values to perform the binding. This means that you cannot change the value in your controller action and expect it to reflect on the view if you use the standard helpers. If there's a value
SelectedRole
in the POST it will always be this value used and the last parameter of the drop down completely ignored.You could write your own helper to achieve this or redirect after the POST.