通过字典在 HTML/Razor 中完全查看和使用它

OTA*_*TAR 1 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;
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

控制器:

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

            myExampleModel myExampleMod = new myExampleModel();

            ViewData["dict"] = myExampleMod.returnDict().Count;
            return View(ViewData);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并查看:

@{
    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>
Run Code Online (Sandbox Code Playgroud)

这有效,我在 html 中看到2

但是我需要将整个Dictionary控制器从控制器传递到视图,因此,当我尝试使用控制器时:

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

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

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

我得到错误:

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

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

Lea*_*res 5

你需要投射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>
Run Code Online (Sandbox Code Playgroud)


Sal*_*eri 5

尝试使用强类型模型(STM)

控制器:

public class myExampleController : Controller
{
    public ActionResult YourAction()
    {
        return View(new YourModelExample());
    }
}
Run Code Online (Sandbox Code Playgroud)

在视图中:

@model Dictionary<int, string>


<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>meth2</title>
</head>
<body>
    <div> 
        <span>@Model.Count</span>
    </div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)