html.dropdownlist不保留所选值 [英] Html.dropdownlist not retaining the selected value

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

问题描述

我在控制器端拥有此代码以初始化下拉列表

I have this code on controller side to initialise the drop down

        List<SelectListItem> items = new List<SelectListItem>();
        items.Add(new SelectListItem
        {Text = "All",
         Value = "All"

        });
        items.Add(new SelectListItem
        {
            Text = "val1",
            Value = "val1"
        });
        items.Add(new SelectListItem
        {
            Text = "val2",
            Value = "val2"
        });

        ViewData["DDLItems"] = items;

        // I have added this code because I am passing the selection back to this     action
        if (Activefilter == null){ Activefilter = "All" ;}

        ViewData["Activefilter"] = Activefilter;

在视图上,我有此代码

 <%= Html.DropDownList("ActiveFilter", (IEnumerable<SelectListItem>)ViewData["DDLItems"], new { onChange = "func(1)" })%>

对于jquery,我有这个

for jquery , I have this

$(document).ready(function() {

                      $('#Activefilter').val(<%= ViewData["Activefilter"].ToString() %>);  
           }

因此,每当我更改下拉列表的值时,就会如上所示调用该操作. viewdata ["Actionfilter"]也采用用户选择的值,但是当控件返回到视图时,

so whenever , i change the value of the dropdown, the action is called as shown above. the viewdata["Actionfilter"] also takes the value selected by the user but when the control comes back to the view,

$('#Filter').val(<%= ViewData["Activefilter"].ToString() %>); 

在此行中,它表示值"All"是未定义的.

in this line , it says the value "All" is undefined.

每次页面重新加载时,我都希望下拉列表保留选定的值.你能帮忙吗?

Everytime, the page reloads, I want the dropdown to retain the selected value. can you please help ?

推荐答案

您可以使用SelectList(),并在构造函数中传递所选项目.而不是使用列表. 被选中的密码

You can use a SelectList() and in the constructor pass the selected item. Instead of using a list. remeber selected

为什么在此示例中未采用所选值,

why is the selected value not being taken in this example,

        List<SelectListItem> items = new List<SelectListItem>();

        items.Add(new SelectListItem
        {
            Text = "All",
            Value = "All"

        });
        items.Add(new SelectListItem
        {
            Text = "val1",
            Value = "val1",
        });
        items.Add(new SelectListItem
        {
            Text = "val2",
            Value = "val2","
        });


        string filter = "val1";
        ViewData["DDLItems1"] = new SelectList(items, "Text", "Value", filter);

查看,这是代码

<div>   @Html.DropDownList("FilterName", (SelectList)ViewData["DDLItems1"])</div>

这是剃刀的语法,如果您不使用剃刀,请切换为<%表示法

That is razor syntax, switch to <% notation if you are not using razor

这篇关于html.dropdownlist不保留所选值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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