MVC Html.Action tutorial with examples

HTML.Action in ASP.NET MVC: A Tutorial with Code Examples. ASP.NET MVC is a popular framework for building web applications. One of the key features of MVC is the ability to reuse and include partial views, which are fragments of HTML that can be used across multiple pages. Html.Action is a powerful helper method that allows you to execute a controller action and render its result within your main view.

In this blog post, we will explore how to use Html.Action to render partial views in ASP.NET MVC.

Step 1: Creating a Controller Action

The first step is to create a controller action that will return the partial view. For demonstration purposes, let's create a simple controller action that returns a list of products.
public class ProductController : Controller
{
    public ActionResult List()
    {
        var products = new List
            {
            new Product { Id = 1, Name = "Product 1", Price = 10.99m },
            new Product { Id = 2, Name = "Product 2", Price = 9.99m },
            new Product { Id = 3, Name = "Product 3", Price = 8.99m }
        };

        return PartialView("_ProductList", products);
    }
}
Step 2: Creating a Partial View

The next step is to create a partial view that will display the list of products. Partial views are typically stored in a folder called Shared within your views directory.
    @model List<product>
    
            @foreach (var product in Model)
            {
            
            }
        
Id Name Price
@product.Id @product.Name @product.Price
Step 3: Calling the Controller Action from Your View

Finally, you can call the controller action from your main view using the Html.Action method. The Html.Action method takes two parameters: the name of the action, and the name of the controller.
    
@Html.Action("List", "Product")
The result of this code will be the rendered HTML for the partial view, which will display a table of products.

Conclusion:

Html.Action is a powerful tool in ASP.NET MVC that allows you to reuse and include partial views within your main views. By using Html.Action, you can keep your views clean and organized, and reduce duplicated code. With a few simple steps, you can easily include partial views in your ASP.NET MVC applications.
 
Best quality Asp .Net Ajax Control Toolkit tutorials.

Give your valuable comments.

Name
Email
Comment
1 + 8 =
 

About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice