如果在 for 循环中,DropDownListFor 不会选择值

发布于 2024-08-28 08:18:21 字数 333 浏览 4 评论 0原文

在我

<%= Html.DropDownListFor( x => x.Countries[ i ], Model.CountryList )%>

的控制器中,

public int[ ] Countries { get; set; }

public List<SelectListItem> CountryList { get; set; }

当表单发布时,没有问题,下拉列表将被填充,并且用户选择的值将被发布。但是,当我尝试加载已为“国家/地区[]”指定值的表单时,它不会被选中。

In my view

<%= Html.DropDownListFor( x => x.Countries[ i ], Model.CountryList )%>

in my controller

public int[ ] Countries { get; set; }

public List<SelectListItem> CountryList { get; set; }

When the forms gets posted there is no problem, the dropdown is populated and the values the user selects are posted. But when I try to load the form with already assigned values to the Countries[ ] it does not get selected.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

硬不硬你别怂 2024-09-04 08:18:21

不确定这是否是 mv4 的新功能或者是否存在于之前的版本中。但是 DropDownListFor 包含一个用于 SelectList 构造函数的附加参数。

SelectList(IEnumerable, String, String, Object)

例如:

Html.DropDownListFor( x => x.Countries[ i ], New SelectList(Model.CountryList,"ID","Description",Model.Countries[i]))

其中 IDCountryList 对象中的国家/地区 ID,Description 是国家/地区名称。

Not sure if this is new to mv4 or if it exists in prior version. But the DropDownListFor includes an additional parameter for the SelectList Constructor.

SelectList(IEnumerable, String, String, Object)

For example:

Html.DropDownListFor( x => x.Countries[ i ], New SelectList(Model.CountryList,"ID","Description",Model.Countries[i]))

Where ID is the Country ID in the CountryList object and Description is the Country Name.

知足的幸福 2024-09-04 08:18:21

我也遇到同样的情况。当使用 foreach 循环 DropDownListFor 时(即在页面上呈现多个选择元素)。

我的解决方法是在控制器而不是视图中设置选定的值:如下所示:

在控制器中:

public class FruitList 
{        
    public int? selectedFruit{ get; set; }
    public List<SelectListItem> fruits
    {
        get
        {
            fruitEntities F = new fruitEntities();
            List<SelectListItem> list = (from o in F.Options
                                         select new SelectListItem
                                         {
                                             Value = o.fruitID,
                                             Text = o.fruit,                                                 
                                             Selected = o.fruitID == selectedFruit
                                         }).ToList();
            return list;
        }
    }
}

public class ViewModel 
{              
    public List<FruitList> collectionOfFruitLists { get; set; }        
}

在视图中

<table>                        
   <% for (int i=0; i < Model.collectionOfFruitLists.Count; i++ )
        { %>
        <tr>                            
            <td><%: Html.DropDownList("fruitSelectList", collectionOfFruitLists[i].fruits, "Please select...") %></td>                
        </tr>
        <%} %>
 </table>

漂亮的一点是控制器中的 Selected = o.fruitID == selectedFruit它的作用类似于 SQL CASE 语句; Lance Fisher 对此进行了很好的解释(谢谢兰斯,你的帖子真的帮助了我:)

I'm getting the same too. When using foreach to loop around a DropDownListFor (i.e. to render multiple select elements on a page).

My work around is to set the selected value in the controller rather than the view: something like this:

In the controller:

public class FruitList 
{        
    public int? selectedFruit{ get; set; }
    public List<SelectListItem> fruits
    {
        get
        {
            fruitEntities F = new fruitEntities();
            List<SelectListItem> list = (from o in F.Options
                                         select new SelectListItem
                                         {
                                             Value = o.fruitID,
                                             Text = o.fruit,                                                 
                                             Selected = o.fruitID == selectedFruit
                                         }).ToList();
            return list;
        }
    }
}

public class ViewModel 
{              
    public List<FruitList> collectionOfFruitLists { get; set; }        
}

In the view

<table>                        
   <% for (int i=0; i < Model.collectionOfFruitLists.Count; i++ )
        { %>
        <tr>                            
            <td><%: Html.DropDownList("fruitSelectList", collectionOfFruitLists[i].fruits, "Please select...") %></td>                
        </tr>
        <%} %>
 </table>

The nifty bit is Selected = o.fruitID == selectedFruit in the controller which acts like a SQL CASE statement; this is really well explained by Lance Fisher (thanks Lance, your post really helped me out :)

风苍溪 2024-09-04 08:18:21

我知道这个问题有点老了,但我刚刚在循环对象列表并尝试将值绑定到编辑视图中的 DropDownListFor(s) 时遇到了这个问题。

我通过使用其他人针对这个问题给出的一些先前解决方案的逻辑,通过内联解决方案克服了这个问题。

绑定到我的模型:

@Html.DropDownListFor(model => model.QuestionActions[i].QuestionActionTypeId,
      Model.QuestionActionTypes.Select(x => new SelectListItem() { Value = x.Value, Text = x.Text, Selected = (x.Value == Model.QuestionActions[i].QuestionActionTypeId.ToString()) }).ToList(),
          "Select Action Type",
                 new { })

Model.QuestionActionTypes 是一个填充在我的控制器中的 SelectList。

I know this question is a bit old but I just came across this problem with looping through a list of objects and attempting to bind the values to DropDownListFor(s) in my Edit View.

I overcame the issue with an inline solution by using the logic from some of the previous solutions given by others for this question.

Binding to my Model:

@Html.DropDownListFor(model => model.QuestionActions[i].QuestionActionTypeId,
      Model.QuestionActionTypes.Select(x => new SelectListItem() { Value = x.Value, Text = x.Text, Selected = (x.Value == Model.QuestionActions[i].QuestionActionTypeId.ToString()) }).ToList(),
          "Select Action Type",
                 new { })

Model.QuestionActionTypes is a SelectList that is populated in my Controller.

留一抹残留的笑 2024-09-04 08:18:21

这有点 hack,并且依赖于 JavaScript,但它对我来说非常有效。

您需要知道字段将生成的客户端 ID(通常可以手动计算这些 ID,但为了安全起见,您可能需要使用类似 FieldIDFor 方法

您只需根据模型设置值即可,在 jQuery 的 $(document).ready 中:

<script type="text/javascript">
    $(document).ready(function () {
        @for(var i = 0; i < 5; i++)
        {
            <text>
                $("#@Html.FieldIDFor(m => m.Countries[i])").val("@Model.Countries[i]");
            </text>
        }
    });
</script>

This is a bit of a hack, and JavaScript reliant but it worked very well for me.

You'll need to know the client IDs that will be produced by the fields (usually these can be worked out manually but for safety you may want to use something like a FieldIDFor method.

You just need to set the values based on the model, in jQuery's $(document).ready:

<script type="text/javascript">
    $(document).ready(function () {
        @for(var i = 0; i < 5; i++)
        {
            <text>
                $("#@Html.FieldIDFor(m => m.Countries[i])").val("@Model.Countries[i]");
            </text>
        }
    });
</script>
赴月观长安 2024-09-04 08:18:21

选择框发送单个值,因此 Countries 属性不应是数组。另外,在您的帖子中,不清楚您在 lambda 表达式中使用的 i 变量来自哪里,并且在帮助程序中使用的这个 x.CountryList 不会编译为 < code>x 未定义。

模型:

public class MyModel
{
    public int SelectedCountry { get; set; }
    public List<SelectListItem> CountryList { get; set; }
}

视图:

<%= Html.DropDownListFor(x => x.SelectedCountry, Model.CountryList) %>

更新:

根据评论,似乎有多个下拉列表。我怀疑问题可能来自于在 for 循环中用作索引的 i 变量。

您可以尝试以下方法:

模型:

public class MyModel
{
    public int[] Countries { get; set; }
    public List<SelectListItem> CountryList { get; set; }
}

视图:

<% foreach (var country in Model.Countries) { %>
    <%= Html.DropDownListFor(x => country, Model.CountryList) %>
<% } %>

A select box sends a single value, so the Countries property should not be an array. Also in your post it is not clear where's the i variable you are using in your lambda expression coming from and this x.CountryList used in the helper won't compile as x is not defined.

Model:

public class MyModel
{
    public int SelectedCountry { get; set; }
    public List<SelectListItem> CountryList { get; set; }
}

View:

<%= Html.DropDownListFor(x => x.SelectedCountry, Model.CountryList) %>

UPDATE:

According to the comment it seems that there are multiple drop downs. I suspect that the problem might come from the i variable used as index in a for loop.

You might try this instead:

Model:

public class MyModel
{
    public int[] Countries { get; set; }
    public List<SelectListItem> CountryList { get; set; }
}

View:

<% foreach (var country in Model.Countries) { %>
    <%= Html.DropDownListFor(x => country, Model.CountryList) %>
<% } %>
可是我不能没有你 2024-09-04 08:18:21

不要在视图模型中使用 IEnumerable,而是使用如下所示的对象列表:

public List<PairVM<string,string>> TiposValorCobertura { get; private set; }

在视图中,当您为循环中的下拉列表分配可选元素时,请这样做:

@Html.DropDownListFor(m => m.Coberturas[i].TipoLimiteInferior, new SelectList(Model.TiposValorCobertura,"Key","Description",  Model.Coberturas[i].TipoLimiteIferior))

其中“Key”和“Description”是 PairVM 的属性

Instead of using a IEnumerable in your viewmodel use a List of objects like this one:

public List<PairVM<string,string>> TiposValorCobertura { get; private set; }

And in your view when you assign the selectable elements for the dropdownlist in the loop, do it this way:

@Html.DropDownListFor(m => m.Coberturas[i].TipoLimiteInferior, new SelectList(Model.TiposValorCobertura,"Key","Description",  Model.Coberturas[i].TipoLimiteIferior))

Where "Key" and "Description" are PairVM's properties

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文