Reputation: 21216
I get the error, that the action doesn't return something in any path.
What would you do, what meaningful could I return? Throw an exception?
[HttpPost]
public virtual ActionResult ActionName(string actionMode, MyViewModel vm)
{
switch (actionMode)
{
case "yes":
return RedirectToAction("actionName1");
case "no":
return RedirectToAction("actionName2", new { data = vm.data });
}
}
Upvotes: 0
Views: 1892
Reputation: 6772
You got an error in switch
because you didn't handle another string values could pass. You can fix it if you specify default behavior like this:
[HttpPost]
public virtual ActionResult ActionName(string actionMode, MyViewModel)
{
switch (actionMode)
{
case "yes":
return RedirectToAction("actionName1");
case "no":
return RedirectToAction("actionName2", new { data = MyViewModel.data });
default:
goto case "yes"; // yes behavior by default
}
}
or like this:
default:
throw new InvalidArgumentException("only 'yes' or 'no' parameter value allowed"); // exception for another values
Another solution is to force your form to pass "True" or "False" values instead of "yes" or "no", and bind it to bool parameter, and use if
operator instead of switch
:
[HttpPost]
public virtual ActionResult ActionName([Bind(Prefix = "actionMode")]bool isYesActionMode, MyViewModel)
// Bind attribute used to get value from old parameter name
{
if (isYesActionMode)
return RedirectToAction("actionName1");
return RedirectToAction("actionName2", new { data = MyViewModel.data });
}
Upvotes: 0
Reputation: 1242
You can write your code as well :-
[HttpPost]
public virtual ActionResult ActionName(string actionMode, MyViewModel)
{
switch (actionMode)
{
case "yes":
return RedirectToAction("actionName1");
default:
return RedirectToAction("actionName2", new { data = MyViewModel.data });
}
}
default will execute when no conditions match.
Upvotes: 0
Reputation: 1698
[HttpPost]
public virtual ActionResult ActionName(string actionMode, MyViewModel)
{
return actionMode == "yes" ? RedirectToAction("actionName1") : RedirectToAction("actionName2", new { data = MyViewModel.data });
}
Upvotes: 0
Reputation: 1018
If your logic is a boolean operation then why not do this?
[HttpPost]
public virtual ActionResult ActionName(string actionMode, MyViewModel)
{
if (actionMode == "yes")
return RedirectToAction("actionName1");
return RedirectToAction("actionName2", new { data = MyViewModel.data });
}
Alternatively, you could throw an exception after the switch statement.
throw new InvalidOperationException();
Upvotes: 1