【问题标题】:Pass dictionary to view and use it in HTML/Razor fully传递字典以在 HTML/Razor 中完全查看和使用它
【发布时间】:2015-11-30 07:51:57
【问题描述】:

这是模型:

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;
        }

    }
}

控制器:

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

            myExampleModel myExampleMod = new myExampleModel();

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

并查看:

@{
    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 从控制器传递给视图,所以,当我在控制器中尝试时:

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

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

&lt;span&gt;@ViewData["dict"].Count&lt;/span&gt;

我得到错误:

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

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

【问题讨论】:

  • 为什么不在视图中使用强类型模型?
  • @ Moo -- @model WebApplication4.Models.myExampleModel -- 我将此代码添加到视图文件中。在这种情况下这是正确的语法吗?
  • 你错过了Dictionary&lt;int, string&gt;的演员表

标签: c# asp.net-mvc dictionary razor


【解决方案1】:

您需要将ViewData["dict"] 转换为Dictionary&lt;int, string&gt;

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

@{
    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>

【讨论】:

    【解决方案2】:

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

    控制器:

    public class myExampleController : Controller
    {
        public ActionResult YourAction()
        {
            return View(new YourModelExample());
        }
    }
    

    在视图中:

    @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>
    

    【讨论】:

      【解决方案3】:

      ViewData 属于 Object。在访问它的属性之前尝试将其转换为Dictionary

      <span>@((ViewData["dict"] as Dictionary<int, string>).Count)</span>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-19
        相关资源
        最近更新 更多