Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 !

like image 416
InspiredBy Avatar asked May 07 '12 17:05

InspiredBy


People also ask

Can we return blank view in MVC?

You can return EmptyResult to return an empty view. You can also just return null .

How do you return a partial view from controller?

In ASP.NET Core MVC, a controller's ViewResult is capable of returning either a view or a partial view. In Razor Pages, a PageModel can return a partial view represented as a PartialViewResult object. Referencing and rendering partial views is described in the Reference a partial view section.

Can we return partial view from action method?

To return a Partial view from the controller action method, we can write return type as PartialViewResult and return using PartialView method.


2 Answers

I have been using

return Content("");

and is working fine.

like image 111
Asif Mushtaq Avatar answered Sep 24 '22 09:09

Asif Mushtaq


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)
    {
    }
}
like image 40
Emanuel Avatar answered Sep 21 '22 09:09

Emanuel