这是我的 Controller 中的代码:
public ActionResult MyMethod(string widgetId)
{
ViewBag.Widget = widgetId;
ViewData["widget"] = widgetId;
return View();
}
这是我在 switch 语句中尝试的内容:
var sort = <%=(string)ViewBag.Widget.ToString() %>;
//switch (<%=(string)ViewData["widget"] %>) {
switch (sort) {
case 'a1':
break;
case 'a2':
break;
case 'a3':
}
在我的例子中,widgetId 是“a3”
它会抛出 a3 未定义的错误。如何解决这个问题?我
最佳答案
我假设这是 JavaScript,服务器值被写入输出:
// 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;
}
关于javascript - 在 switch 语句中使用 ViewBag,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15084889/