0

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

petko_stankoski
  • 10,459
  • 41
  • 127
  • 231

3 Answers3

2

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;
}
Tim M.
  • 53,671
  • 14
  • 120
  • 163
1

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
K D
  • 5,889
  • 1
  • 23
  • 35
0

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() %>';
Daniel Imms
  • 47,944
  • 19
  • 150
  • 166