Hello,Can we use Nested switch case in C# or switch case under if else case in ASP.NET C#? If yes, can anyone provide an example? I have been successfully able to redirect users to certain pages depending on the basis of the ratings. Now I want to redirect them depending on the basis of the ratings as well as DestinationID. I have attached the code for redirecting users depending on the ratings done by them.
[HttpPost]
public ActionResult Register(FormCollection collection) //UserRating ratingModel
{
int rating = Convert.ToInt32(collection["Rating"]);
switch (rating)
{
case 1:
return RedirectToAction("RecommendationPlaces");
break;
case 2:
return RedirectToAction("RecommendationPlaces2");
break;
case 3:
return RedirectToAction("RecommendationPlaces3");
break;
case 4:
return RedirectToAction("RecommendationPlaces4");
break;
case 5:
return RedirectToAction("RecommendationPlaces5");
case 6:
return RedirectToAction("RecommendationPlaces6");
case 7:
return RedirectToAction("RecommendationPlaces7");
case 8:
return RedirectToAction("RecommendationPlaces8");
case 9:
return RedirectToAction("RecommendationPlaces9");
case 10:
return RedirectToAction("RecommendationPlaces10");
default:
return RedirectToAction("RecommendationPlaces11");
}
Hello, you can use nested switch case for better output or you can also use Nested-If, here is the general C# syntax of nested Switch
switch(ID1) {
case 'A':
Console.WriteLine("This A is part of outer switch" );
switch(ID2) {
case 'A':
Console.WriteLine("This A is part of inner switch" );
break;
case 'B': /* inner B case code */
}
break;
case 'B': /* outer B case code */
}
So, in your controller code you can have code something like this
public ActionResult Index()
{
int rating = 1;
int DestinationId = 2;
switch (rating)
{
case 1:
switch (DestinationId)
{
case 2:
//this will redirect to action Case2 directly and no other options will be executed
return RedirectToAction("Case2");
}
break;
case 2:
switch (DestinationId)
{
case 3:
return RedirectToAction("Case3");
}
break;
}
return View();
}
Let me know if it resolves your query, you can comment on the answer, thanks
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly