Shared Views in Asp.net MVC

Shared Views in Asp.net MVC
Shared view is a view file (.cshtml) that is not tied to a specific controller or action. These views typically reside in the Views/Shared folder and are designed to be reused across different controllers or even multiple projects.
 
Why Use Shared Views?
Reduce Duplication: Avoid writing the same code repeatedly for common UI elements across your application.
Consistent UI: Maintain a unified look and feel across different pages and sections of your site.
Simplified Maintenance: Update the shared view once, and the changes automatically apply to all views that use it.
 
How Shared Views Work
Location: By default, ASP.NET Core MVC looks for shared views in the Views/Shared folder. You can also create subfolders within Views/Shared to further organize your shared views.
 
Naming: Name your shared views in a way that reflects their purpose or content. Common examples include:
_Layout.cshtml: The main layout for your application’s pages.
_PartialName.cshtml: Smaller, reusable components (partial views) that can be embedded in other views.
 
Rendering: You can render a shared view using the following approaches:
PartialView(): Renders a partial view.
View(): Can be used to render a shared view directly, but it’s more common to use PartialView() for partial views and reserve View() for full pages.
 
 
Code Example: Shared View All.cshtml
<!DOCTYPE html>
<html>
<head>
    <title>All Products</title>
    <meta charset=”UTF-8″ />
    <link href=”~/StyleSheet.css” rel=”stylesheet” />
</head>
<body>
    <div class=”page-content”>
        <h1>All Products</h1>
        </div>
</body>
</html>
This shared view (All.cshtml) can be reused by multiple controllers to display the “All Products” page with the same structure and styling.
 
 
Code Example: Controllers Using the Shared View
// HomeController.cs
[Route(“home/all-products”)]
public IActionResult All()
{
    return View(); // Will look for Views/Home/All.cshtml first, then Views/Shared/All.cshtml
}
 
// ProductsController.cs
[Route(“products/all”)]
public IActionResult All()
{
    return View(); // Will look for Views/Products/All.cshtml first, then Views/Shared/All.cshtml
}
In both HomeController and ProductsController, the All action method returns a ViewResult. ASP.NET Core will first look for a view named All.cshtml within the specific controller’s view folder (e.g., Views/Home or Views/Products). If it doesn’t find it there, it will look for it in the Views/Shared folder.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply