下拉项目更改时显示MVC中的工具提示

时间:2011-12-20 20:30:33

标签: jquery asp.net-mvc

我有一个用于创建下拉列表的选择列表,我已经连接了jquery以在更改时获取所选项的值。这一切都有效。

我的目标是在下拉菜单中更改项目时显示长文本。这不能存储在选项html标记中,因为没有受支持的属性可以在HTML中完成此操作(根据我的理解)。

所以我需要一些如何将字典对象从MVC返回到我的页面。我想在页面上有这些数据。我不希望每次项目发生变化时都要拨打远程电话。

我的问题是我不知道如何做到这一点。在我的控制器中,我必须返回实际下拉列表中的项目列表以及需要显示的其他数据。所以我执行了一个“返回视图(mymodel);”我不知道如何将此服务器端字典对象传递给客户端,以便javascript可以与它进行交互。有人可以通过一个关于javascript如何访问它的例子给我一些关于如何序列化这个对象的技巧吗?

谢谢!

1 个答案:

答案 0 :(得分:4)

您可以使用隐藏字段将信息存储在html中,并使用jquery循环显示它们。

例如,在您的控制器中,您可以拥有:

    public class Default1Controller : Controller
{
    //
    // GET: /Default1/

    public ActionResult Index()
    {
        Dictionary<string, string> dict = new Dictionary<string, string>();

        dict.Add("cat", "the cat is in the hat.");
        dict.Add("dog", "the dog is hiding under the fence.");
        dict.Add("mat", "the cat and the dog get hair on the mat.");

        return View("ViewPage1.cshtml", dict);

    }

}

你的观点可能有这个:

@model Dictionary<string, string>

@{
    List<string> keys = new List<string>(Model.Keys);
    foreach (string key in keys)
    {
        <input id="@key" type="hidden" class="dictionary" value="@Model["key"]"   />                
    }
}

然后在你的项目内部更改了jquery事件,你可以使用class =“dictionary”循环隐藏字段,如果id =所选项目的文本,则使用它们...

$(".dictionary").each(function(){
    if(this.attr("id") == selectedItem){
        //display logic for the hidden field's value
    }
});

希望这有帮助。

相关问题