Pregunta

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

¿Fue útil?

Solución

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

Otros consejos

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

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() %>';
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top