Tuesday, June 15, 2010

Understanding Models part 2: Data Binding and Strongly Typed Views

In the previous post we introduced a simple MVC model. Another approach to implement model is associating the model with a strongly typed view.

Remember the GetData from the previous post, the last line returned a simple view that displayed the string “Thanks”
returnView("Thanks");

now we will implement a strong typed view to display data from the model Products, so here are the steps
  1.  Go to the views folder, go to products folder, right click and choose add view.
  2. You’ll see a dialogue like this, we will call it StrongProducts, then choose the view data class which is our Products Model, then choose empty content and finally choose our master page.

  3. Go to the page you will notice that it inherits from
    Inherits="System.Web.Mvc.ViewPage<CustomersOrders.Models.Product>" %>
    Instead of
    Inherits="System.Web.Mvc.ViewPage" %>

  4. Add the following to the page
    <p>
      Thanks, you just entered <%=Model.Name%>
    </p>
    

  5. Now in the controller class
    ProductsController 
    change the GetData method to be
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult GetData()
    {
    Product NewProduct = new Product();
    NewProduct.Name = Request["txtName"].ToString();
    NewProduct.Description = Request["txtDesc"].ToString();
    Product.InsertProduct(NewProduct);
     
    //returns a strongly typed view
    return View("StrongProducts", NewProduct);
    } 

  6. Now browse to products page, add a new product then you will be redirected to StrongProducts view. It should be like this

  7. So what happened here: first the strongly typed view is associated with the Products Model, this means that you can use all of your model’s properties and methods in your view and bind them with the controls on the view by referencing the Model property of the view.

Advantages of using strongly typed views:
  1. Better than using loosely typed dictionaries (such as the ViewData ) as it expresses what should the view do. There would be no confusion on what data the view should deal with.
  2. Makes use of Model Binding feature of the MVC framework (link to another post).
  3. Makes use of the intellisense feature so visual studio can help you in development

No comments:

Post a Comment