Andre Roque
Andre Roque

Reputation: 543

Using ViewData in Javascript code

I'm creating a ViewData in an ASP.Net Controller like this:

var elements = db.Requests.GroupBy(user => user.submitUser)
                   .Select(slt => new { UsersCount = slt.Key, CountReq = slt.Count() });

this will have for example

UsersCount      Count

user1           3

user2           3

user3           3

Then in Javascript I want to create an array with UsersCount and Count, for example:

var arrayUsers = ViewData.UsersCount;
var arrayCounter = ViewData.CountReq;

I already tried several solutions and I can't do it. What's the best solution?

CONTROLLER:

 public ActionResult Statistics()
        {
            var elements = db.Requests.GroupBy(user => user.submitUser)
                            .Select(slt => new { UsersCount = slt.Key, CountReq = slt.Count() });


            ViewData["usersCounter"] = elements;

            return View();
        }

Javascript in VIEW

<script>
    var check = @ViewData["usersCounter"]**;**error

....

}

Upvotes: 1

Views: 10131

Answers (3)

fdomn-m
fdomn-m

Reputation: 28611

The code

@ViewData["usersCounter"]

will effectively do this:

@ViewData["usersCounter"].ToString()

You're setting your viewdata to the result of a select, so the .ToString wil output the generic generic type name directly to the output.

Simply check the source code of the rendered page to see what is being rendered.

Also, specify the 'error' that you get.

If you only change your code to

var check = '@ViewData["array"]'

(as per other answers) then 'check' will not contain the list, only the list.tostring()

If you want to copy the whole list into a js variable, you'll need to serialise it first, eg, something like (with JSON nuget package installed):

var check = @(Newtonsoft.Json.JsonConvert.SerializeObject(ViewData["array"]));

To note: many people will recommend that you use a ViewModel rather than ViewData as it's strongly typed as generally easier to work with / maintain.

However, is there as reason you need/want this in javascript? The GroupBy and Select, even after converting to js aren't really js, and are better suited for working with c# or @{} statements.

Upvotes: 1

Canvas
Canvas

Reputation: 5897

Andre have you tried

var check = '@ViewData["array"]'

Upvotes: 0

code
code

Reputation: 1137

To use ViewData in a javascript tag just prefix ViewData with the @ symbol

var check = @ViewData["array"]

In your controller

ViewData["array"] = elements;

Why not just set the variable to your model since it looks like you're setting it to that

var check = @Html.Raw(Json.Encode(Model));

Then you can do whatever

var blur = check.UserName

Upvotes: 1

Related Questions