Search code examples
javascriptasp.net-mvcswitch-statementviewdataviewbag

Using ViewBag in a switch statement


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


Solution

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