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.
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).
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.
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.
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!
Try casting, the compiler doesn't know the return type of ToString() because it is dynamic.
var sort = (string)ViewBag.Sort.ToString();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With