Oto Shavadze
Oto Shavadze

Reputation: 42753

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

This is model:

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

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

This works, and I see in html 2.

But I need pass whole Dictionary from controller to view, so, when I try in controller:

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

and In HTML/Razor I try counting of Dictionary elements:

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

I get error:

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

Question: what I am missed here?

Upvotes: 1

Views: 17543

Answers (3)

Saleh Bagheri
Saleh Bagheri

Reputation: 434

try using Strongly-Typed Model (STM)

Controller:

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

in View:

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

Upvotes: 5

Sateesh Pagolu
Sateesh Pagolu

Reputation: 9606

ViewData is of Object. Try casting this to Dictionary before accessing it's property

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

Upvotes: 3

Leandro Soares
Leandro Soares

Reputation: 2972

You need to cast ViewData["dict"] to Dictionary<int, string>

Normally I create a variable in the page top section.

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

Upvotes: 5

Related Questions