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
- Go to the views folder, go to products folder, right click and choose add view.
- 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.
- 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" %>
- Add the following to the page
<p> Thanks, you just entered <%=Model.Name%> </p>
- 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);
}
- Now browse to products page, add a new product then you will be redirected to StrongProducts view. It should be like this
- 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:
- 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.
- Makes use of Model Binding feature of the MVC framework (link to another post).
- Makes use of the intellisense feature so visual studio can help you in development