Mvc razor dropdownlist html helper重置选定的值 [英] Mvc razor dropdownlist html helper resets selected value

查看:84
本文介绍了Mvc razor dropdownlist html helper重置选定的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个让我摸不着头脑,因为我还是MVC和Razor的新手。我正在动态构建一些选择项目列表,其中有一个项目是预选的,没有大问题。得到的是,在将列表传递给Html帮助函数后,所选项目将被取消选择,列表默认为第一项。单步执行页面加载,List< SelectListItem>在进入辅助函数之前具有正确的值。我使用实体框架进行数据库操作。



This one has got me scratching my head as I'm still pretty new to MVC and Razor. I'm building a couple of Select Item lists dynamically that have one item pre-selected, no biggie. What is getting me is that after the list is passed into the Html helper function, the selected item is being de-selected and the list defaults to the first item. Stepping through the page load, the List<SelectListItem> has the correct values prior to entering the helper function. I'm NOT using the Entity Framework for database operations.

<td>
  @{
    List<SelectListItem> itemList = Functions.GetListForProperty(property);
  }
  <% Correct value is selected in the list %>
  @Html.DropDownList("PropertyList", itemList)
  <% Selected = false for the previously selected item, wtf? %>
</td>





我在这里缺少一些设置。视图是使用脚手架构建的,但我有其他视图,动态生成的下拉列表不会这样做。



我尝试过:



我尝试了两种辅助函数,@ Html.DropDownListFor(Model => model.property,IEnumerable< SelectListItem>)和@ Html.DropDownList(Name,IEnumerable< SelectListItem>)并得到相同的结果。我甚至已经内联了构建列表的代码并且仍然得到了相同的东西。



Is there some setting I'm missing here. The view is built with the scaffolding but I have other views with dynamically generated drop down lists that don't behave this way.

What I have tried:

I've tried both flavors of the helper function, @Html.DropDownListFor(Model => model.property, IEnumerable<SelectListItem>) and @Html.DropDownList("Name", IEnumerable<SelectListItem>) and get the same results. I have even inlined the code that builds the list and still get the same thing.

推荐答案

找出我的问题。事实证明是非常简单的事情。问题在于视图包。



@ Html.DropDownListFor(Model => Model.Property,selectList)的问题是Model.Property不是类型List< SelectListItem>所以当ViewBag在响应中呈现视图时它不会被绑定。



@ Html.DropDownList(PropertyName,selectList)的问题是我是为它分配与为其获取数据的属性相同的名称。将Name字符串更改为PropertyNameSelect之后,所选值正确呈现为http响应字符串。
Figured out my problems. Turns out is was something very simple. The problem was with the view bag.

Problem with @Html.DropDownListFor(Model => Model.Property, selectList) is that the Model.Property was not of the type List<SelectListItem> so it wouldn't be bound when the ViewBag rendered the view in the response.

Problem with @Html.DropDownList("PropertyName", selectList) is that I was assigning it the same name as the property it was fetching data for. Once I changed the Name string to something like "PropertyNameSelect," the selected values rendered correctly to the http response string.


这篇关于Mvc razor dropdownlist html helper重置选定的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆