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?
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 .
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.
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.
To return a Partial view from the controller action method, we can write return type as PartialViewResult and return using PartialView method.
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); ... }
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.
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