Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if (partial) view exists from HtmlHelperMethod

Tags:

c#

asp.net-mvc

Does anyone know if it's possible to check if a partial view exists from within an HtmlHelperExtension?

I know it's possible from a controller using the following:

 private bool ViewExists(string name)  {      ViewEngineResult result = ViewEngines.Engines.FindView(ControllerContext, name, null);      return (result.View != null);  } 

Source: Does a View Exist in Asp.Net MVC?

But you can't do the above in a helper, as you don't have access to the controller context. Any thoughts on how to do this?

like image 780
Sam Shiles Avatar asked Apr 25 '13 10:04

Sam Shiles


People also ask

How do you find partial view?

A partial view is sent via AJAX and must be consumed by JavaScript on the client side, while a View is a full postback. That's it. Normally this means that a View is more of a complete web page and a partial view is reserved for individual sections or controls. Realistically, though, you can send the exact same .

Can you define partial view in MVC?

A partial view is a Razor markup file ( . cshtml ) without an @page directive that renders HTML output within another markup file's rendered output. The term partial view is used when developing either an MVC app, where markup files are called views, or a Razor Pages app, where markup files are called pages.

Where are partial views stored?

You can place the partial view in the Shared folder or you can store it under the controller-specific subfolder. It would to shared if used by multiple controllers and it would better go to the controller view folder if only used by a single controller.

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

But you can't do the above in a helper, as you don't have access to the controller context.

Oh yes, you do have access:

public static HtmlString MyHelper(this HtmlHelper html) {     var controllerContext = html.ViewContext.Controller.ControllerContext;     var result = ViewEngines.Engines.FindView(controllerContext, name, null);     ... } 
like image 60
Darin Dimitrov Avatar answered Oct 07 '22 12:10

Darin Dimitrov


For completeness, the way to find a partial view, is actually as follows.

public static HtmlString MyHelper(this HtmlHelper html) {      var controllerContext = html.ViewContext.Controller.ControllerContext;      ViewEngineResult result = ViewEngines.Engines.FindPartialView(controllerContext, name);      ... } 

And be sure to include the extension of the view; either cshtml for razor or aspx for webforms view engines.

like image 31
Sam Shiles Avatar answered Oct 07 '22 14:10

Sam Shiles