这是模型:
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/