簡體   English   中英

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

[英]Pass dictionary to view and use it in HTML/Razor fully

這是模型:

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元素:

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

ViewDataObject 嘗試在訪問它的屬性之前將其轉換為Dictionary

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

嘗試使用強類型模型(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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM