Reputation: 10723
Here is the code in my controller:
public ActionResult MyMethod(string widgetId)
{
ViewBag.Widget = widgetId;
ViewData["widget"] = widgetId;
return View();
}
And here is what I tried in the switch statement:
var sort = <%=(string)ViewBag.Widget.ToString() %>;
//switch (<%=(string)ViewData["widget"] %>) {
switch (sort) {
case 'a1':
break;
case 'a2':
break;
case 'a3':
}
In my case, the widgetId is 'a3'
And it throws error that a3 is undefined. How to fix this? I
Upvotes: 0
Views: 1887
Reputation: 5989
You should use it in following way while working in javascript..
var sort = "<%=ViewBag.Widget.ToString() %>";
considering your viewbag value as "a3" above statement will produce
var sort = "a3"; // so JS could evaluate it as string.
In your previous statement it was producing it like following
var sort = a3; // Where JS was not having any idea about what a3 is
Upvotes: 1
Reputation: 50229
You're missing the quotes around the js string. So the server passed the value a3
is undefined on the client side.
var sort = '<%=(string)ViewBag.Widget.ToString() %>';
Upvotes: 0
Reputation: 54377
I'm assuming this is JavaScript with a server value being written into the output:
// you were missing quotes around the value of "sort"
// (single or double quotes are fine since this is JS)
var sort = "<%= ViewBag.Widget.ToString() %>";
alert(sort);
switch (sort) {
case 'a1':
break;
case 'a2':
break;
case 'a3':
break;
}
Upvotes: 2