Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return new EmptyResult() VS return NULL

in ASP.NET MVC when my action will not return anything I use return new EmptyResult() or return null

is there any difference?

like image 811
Artur Keyan Avatar asked Dec 19 '11 12:12

Artur Keyan


People also ask

How do I return EmptyResult?

EmptyResult is used when you want to execute logic return inside the controller action method but does not want any result back to the view then EmptyResult return type is very important . It does not return any output to the browser. It shows the empty result set to the browser without adding the view.

Can we return blank view in MVC?

@RobinMaben: No, null would not return an object from the method.

Can I return ActionResult instead of ViewResult?

When you set Action's return type ActionResult , you can return any subtype of it e.g Json,PartialView,View,RedirectToAction.

Which one of the following is are method's of EmptyResult class?

The EmptyResult is a class in MVC which does not return anything, like Void method . EmptyResult is used when you want to execute logic written inside the controller action method but does not want any result back to the view then EmptyResult return type is very important . It does not require to add the view.


1 Answers

You can return null. MVC will detect that and return an EmptyResult.

MSDN: EmptyResult represents a result that doesn't do anything, like a controller action returning null

Source code of MVC.

public class EmptyResult : ActionResult {      private static readonly EmptyResult _singleton = new EmptyResult();      internal static EmptyResult Instance {         get {             return _singleton;         }     }      public override void ExecuteResult(ControllerContext context) {     } } 

And the source from ControllerActionInvoker which shows if you return null, MVC will return EmptyResult.

protected virtual ActionResult CreateActionResult(ControllerContext controllerContext, ActionDescriptor actionDescriptor, object actionReturnValue) {     if (actionReturnValue == null) {         return new EmptyResult();     }      ActionResult actionResult = (actionReturnValue as ActionResult) ??         new ContentResult { Content = Convert.ToString(actionReturnValue, CultureInfo.InvariantCulture) };     return actionResult; } 

You can download the source code of the Asp.Net MVC Project on Codeplex.

like image 50
dknaack Avatar answered Sep 23 '22 15:09

dknaack