RedirectToAction () vs. View () and ternary operators?

when deciding which ActionResult to return from the controller action, I decided to use ternary operators as opposed to the longer if-else. Here is my problem ...

this code works

return ModelState.IsValid ? (ActionResult) RedirectToAction("Edit", new { id = id }) : View(new EditViewModel(updatedCategory)); 

But it is not

 return ModelState.IsValid ? RedirectToAction("Edit", new { id = id }) : View(new EditViewModel(updatedCategory)); 

I did not need to do explicit casting when using if-else. In addition, both RedirectToAction () and View () return a derived ActionResult.

I like the compression of this code, but the casting seems wrong. Can anyone enlighten me?

Although I'm sure this is obvious, EditViewModel is the view model for my Edit action, and updatedCategory is an EF4 object. But I do not think this is relevant to the problem.

ok ... I just realized what I was doing was not necessary, because, regardless of whether I return to the "Edit" action with the updated category, I do not need to check whether the model is valid. I'm still curious to know the answer to the question if anyone can help.

+6
asp.net-mvc actionresult
source share
2 answers

I believe, because the arguments when using the ?: operator must be convertible among themselves, for example. capable of? x: y you need to convert x to y or y to x. Then the type of result is the least specific of the two. Therefore, if x was an object and y a string, you can pass the string to the object, and the result will have an object of type.

In your example, x is RedirectToRouteResult and y is ViewResult. You cannot convert RedirectToRouteResult to ViewResult or vice versa. You can convert both of them to ActionResult, so if you use ActionResult, then it works - the type x is ActionResult, y can be converted to ActionResult, and the overall result is of type ActionResult.

I hope I explained it right there ... I'm afraid I don’t know the exact semantics of the operator ?: because I rarely use it myself ...

+9
source share

The data types must be exactly the same in the destination variable, and both return types here are the simplest example I can think of:

 int originalValue = 10; int? value = (originalValue != 10) ? null : originalValue; //Which is very easily fixed with type casting as you have done int? value = (originalValue != 10) ? null : (int?)originalValue; 
0
source share

All Articles