c# - 传递字典以在 HTML/Razor 中完全查看和使用它

标签 c# asp.net-mvc dictionary razor

这是模型:

namespace WebApplication4.Models
{
    public class myExampleModel
    {
        Dictionary<int, string> dict = new Dictionary<int, string>();

        public Dictionary<int, string> returnDict ()
        {

            dict.Add(0,"a");
            dict.Add(1,"b");
            return dict;
        }

    }
}

Controller :

namespace WebApplication4.Controllers
{
    public class myExampleController : Controller
    {
        public ActionResult meth2()
        {

            myExampleModel myExampleMod = new myExampleModel();

            ViewData["dict"] = myExampleMod.returnDict().Count;
            return View(ViewData);
        }
    }
}

和 View :

@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>meth2</title>
</head>
<body>
    <div> 
        <span>@ViewData["dict"]</span>
    </div>
</body>
</html>

这行得通,我在 html 中看到了 2 .

但我需要通过整个 Dictionary从 Controller 到 View ,所以,当我在 Controller 中尝试时:

ViewData["dict"] = myExampleMod.returnDict(); return View(ViewData);

在 HTML/Razor 中,我尝试计算 Dictionary元素:

<span>@ViewData["dict"].Count</span>

我得到错误:

'object' does not contain a definition for 'Count'...

问题:我在这里错过了什么?

最佳答案

你需要投ViewData["dict"]Dictionary<int, string>

通常我会在页面顶部创建一个变量。

@{
    Layout = null;
    var Dictionary = (Dictionary<int, string>)ViewData["dict"];
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>meth2</title>
</head>
<body>
    <div> 
        <span>@Dictionary.Count</span>
    </div>
</body>
</html>

关于c# - 传递字典以在 HTML/Razor 中完全查看和使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32393237/

相关文章:

c# - Entity Framework 6.0 原始 SQL 以查看模型

c# - 如何在 MVC 中使用 GET 方法进行搜索

c# - DisplayNameFor 用于从 IEnumerable<T> 派生的接口(interface)

python - 顺序处理比池处理更快

python - 以特定格式将 "dictionary of dictionaries"写入 .csv 文件

c# - 如何在关闭表单之前验证表单的控件?

c# - 使用 C#/Windows API 的虚拟键盘 - 发送键输入,但不获取焦点

python - 在 python 中对字典的字典列表进行排序

c# - 静音 dotnet cli 输出中的所有警告

c# - 通过 WIF 在 MVC 应用程序之间共享身份验证