Tuesday, June 5, 2012

MVC - UserControl and passing data from a page to it

Using UserControl makes your application pretty powerful, because you can reuse some stuff that you already created easily.

In MVC , View talks with controller to return Model as data. this is a general concept in MVC and I dont want to discuss about lots of possibilities we may have in .

Let's start creating our UserControl on PartialView in MVC , Consider we want to put productDetail information in a usercontrol and then wherever we need productInfo then easily use our existing usercontrol.

1- Add a folder under View and name it Product.
2- Add a PartialView(UserControl) name it ProductDetailInfo.ascx.this is a strongly typedusercontrol means if you see it is inheriting from ProductModels.ProductInfo , if it was not inheriting from anything it was not strongly typed then you can not say Model.ID then you needed to use ViewData["ProductInfo.ID"]

3- Add a View(Page) name it Detail.(just need to put ProductDetailInfo.ascx. into the page.) the name if the page is the same as the controller method name in productController or in the productController when it wants to return the data we could specify the view to return as well.
in the page just add the following line to add usercontol into the page
This page is responsible to get the data and pass the required data to the usercontrol. in this example it passes all model to the usercontrol.

1- Add a controller class for product name it ProductController.
2- Add a new Method in the class with the following structure
public class ProductController : Controller
 public ActionResult Detail(int productID)
 ProductModels.ProductInfo productInfo = new ProductModels.ProductInfo();

  productInfo.Price = 18;
   productInfo.ID = 1;
   productInfo.Name = "Monitor";
  return View(productInfo);


1- Add a new Model name it ProductModels
2- Add a new Class into it wit the following info

    public class ProductModels
        public class ProductInfo
            public int ID { set; get; }

            public string Name { set; get; }

            public int Price { set; get; }

Now Its time to press F5 and see what you have done.

1 comment:

  1. This comment has been removed by a blog administrator.


Thank you for sharing your knowledge and experiences with this weblog.