Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a switch statement on a string fail when the value comes from ViewBag?

I have the following code in a CSHTML razor page:

@{
    var sort = ViewBag.Sort.ToString();
    switch (sort)
    {
        case "None": Html.Action("SortNone"); break;
        case "Name": Html.Action("SortName"); break;
        case "Date": Html.Action("SortDate"); break;
    }
}

However, this is failing with a Compiler Error Message:

CS0151: A switch expression or case label must be a bool, char, string, integral, enum, or corresponding nullable type

But sort is a string! Rewriting this as a series of if/else statements works, but is not as elegant.

like image 878
Darren Oster Avatar asked Jun 18 '12 23:06

Darren Oster


People also ask

How does a ViewBag work?

In general, ViewBag is a way to pass data from the controller to the view. It is a type object and is a dynamic property under the controller base class. Compared to ViewData, it works similarly but is known to be a bit slower and was introduced in ASP.NET MVC 3.0 (ViewData was introduced in MVC 1.0).

How do you show ViewBag value in view?

To pass the strongly typed data from Controller to View using ViewBag, we have to make a model class then populate its properties with some data and then pass that data to ViewBag with the help of a property. And then in the View, we can access the data of model class by using ViewBag with the pre-defined property.

How to use ViewBag in c# MVC?

ViewBag uses the dynamic feature that was introduced in to C# 4.0. It allows an object to have properties dynamically added to it. Internally, it is a dynamic type property of the ControllerBase class which is the base class of the Controller class. ViewBag only transfers data from controller to view, not visa-versa.

How to call a function in switch case in javascript?

var minerals = ['dirt', 'rock', 'gold']; for (var i = 0; i < minerals. length; i++) { var mineral = minerals[i]; switch (mineral) { // this will see a string value, in this example, for each item of the array case isGold (mineral): console. log('We struck gold!


1 Answers

Try casting, the compiler doesn't know the return type of ToString() because it is dynamic.

var sort = (string)ViewBag.Sort.ToString();
like image 64
Rohan West Avatar answered Sep 27 '22 22:09

Rohan West