in ASP.NET MVC when my action will not return anything I use return new EmptyResult()
or return null
is there any difference?
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.
@RobinMaben: No, null would not return an object from the method.
When you set Action's return type ActionResult , you can return any subtype of it e.g Json,PartialView,View,RedirectToAction.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With