Using Partial View in ASP.NET MVC3

1. Create a new project and set project name is MvcApplications.PartialView

image

2. Create a new class Product in Models folder

 public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public float Price { get; set; }
    }

3. Create a new ProductViewModel in Models folder

public class ProductViewModel
    {
        public Product Pro;
    }

4. Create _FeaturedProduct partial view

Right click Shared folder –> add View. Sure Create as partial view checkbox is checked

image

So it is detail cshtml file:

@model MvcApplications.PartialView.Models.Product

<style type="text/css"> 
    .featuredProduct {border: solid 1px #000} 
</style>

<div> 
    <div> 
        <h2> 
            Our Featured product:<br /> 
            @ViewBag.FeaturedProduct.Name 
        </h2> 
    </div>    
    <div> 
        <h3> 
            Now discounted to $@String.Format("{0:F}", ((decimal)ViewBag.FeaturedProduct.Price)-100) 
        </h3> 
    </div>   

</div>

5. Call Partial view from Index view

<div>
  @Html.Partial("_FeaturedProduct")
</div>

6. In controller code-behind

ProductViewModel productModel = new ProductViewModel();

        public ActionResult Index()
        {
            ViewBag.FeaturedProduct = new Product() {Id = 1, Name = "HTC Trophy", Price= 400 };

            return View(productModel.Pro);
        }

7. Build solution and run

image

Advertisements
This entry was posted in ASP.NET MVC. Bookmark the permalink.

2 Responses to Using Partial View in ASP.NET MVC3

  1. Pingback: Using Partial View to implement Search Bar in ASP.NET MVC3 | quysnhat's blog

  2. moibe says:

    Thanks, very useful for my developement.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s