InspiredBy
InspiredBy

Reputation: 4320

Clean way to return an empty mvc partial view

In cshtml file, based on a condition, what's the best way to return an empty partialview ?

Right now I have:

@if(Model.Count() > 0)
{
  loooonng partial view block of markup code
}

How can I re-do it to look cleaner closer to this:

@if(Model.Count() == 0)
{
  render an empty partial view
}

  loooonng partial view block of markup code goes here   <- This will obviously get executed only if Model.Count() > 0

Thanks in advance !

Upvotes: 19

Views: 22161

Answers (5)

Dimskiy
Dimskiy

Reputation: 5301

A view should not decide if it should be empty or contain something. A view should be as "dumb" as possible, simply displaying the data from the model in a "fancy" way. It is up to the controller to decided if the output should be empty or contain some data to display. In other words, it is up to the controller to return an empty view or a non-empty view.

Solution

Create an empty view (empty *.cshtml file) under Views/Shared:

MVC_Project 
├── Views
    ├── Shared
        ├── _Empty.cshtml

Controller code:

public virtual PartialViewResult SomeAction()
{
    //some condition to determine if the view should be empty
    //maybe check if some properties of the model are null?
    if(returnEmptyView) 
        return PartialView("~/Views/Shared/_Empty.cshtml");

    return PartialView("~/Views/Something/NormalView.cshtml", model);
}

Upvotes: 1

Chris
Chris

Reputation: 2646

If you're returning a PartialViewResult I found that in the controller you can use

return default(PartialViewResult);

or

return null;

without any problems. The only consideration I can think is if you are using

var partialView = Html.Action("Action", "Controller");

in your view then you will need to check for null. Html.RenderAction appears to accept it no problem.

Upvotes: 14

Backs
Backs

Reputation: 24903

Use EmptyResult class:

return new EmptyResult();

Upvotes: 5

Emanuel
Emanuel

Reputation: 626

Not sure if you still need an answer, but I came across this problem and here's what I did in the view:

@if(Model.Count() == 0)
{
return; // a simple return will stop execution of the rest of the View
}

On a Controller level, I created a new class and returned it in my action:

public class EmptyPartialViewResult : PartialViewResult
{
    public override void ExecuteResult(ControllerContext context)
    {
    }
}

Upvotes: 15

Asif Mushtaq
Asif Mushtaq

Reputation: 13150

I have been using

return Content("");

and is working fine.

Upvotes: 17

Related Questions