Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

when deciding on which ActionResult to return from a Controller Action I decided to use the ternary operators as opposed to the lengthier if-else. Here is my issue...

this code works

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

but this doesn't

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

I would not have to do the explicit casting if using an if-else. Plus both RedirectToAction() and View() return an ActionResult derivative.

I like the terseness of this code but that casting doesn't seem right. Can anyone enlighten me?

Though I'm sure this is obvious, the EditViewModel is a view model for my Edit action and updatedCategory is an EF4 object. But I don't think this is relevant to the issue.

ok... I just realized what I was doing is unnecessary because regardless I am going back to the Edit action with the updatedCategory, so I don't need to make sure the Model is valid. I am still curious to know the answer to the question if anyone can help.

like image 913
Derrick W Avatar asked Jan 28 '11 14:01

Derrick W


1 Answers

I believe it's because the arguments when using the ?: operator have to be convertable between themselves, e.g. in condition ? x : y you need to be able to convert x to y or y to x. Then the type of the result is the least specific of the two. So if x was an object and y a string then you can cast a string to an object and the result would be of type object.

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

Hope I've explained myself correctly there... Afraid I don't know the exact semantics of the ?: operator as I rarely use it myself...

like image 85
MrKWatkins Avatar answered Oct 20 '22 18:10

MrKWatkins