O'Reilly logo

ASP.NET 4 24-Hour Trainer by Toi B. Wright

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 20B. Managing Data in MVC

In lesson 19B I showed you how to display data using the ASP.NET MVC framework. In this lesson I show you how to create a new record, update a record, and delete a record using the Entity Data Model that was created in Lesson 18.

ADDING RECORDS

This is the default scaffolding that ASP.NET MVC provides for the Create action method:

//
// GET: /Category/Create

public ActionResult Create()
{
    return View();
}

//
// POST: /Category/Create

[HttpPost]
public ActionResult Create(FormCollection collection)
{
    try
    {
         // TODO: Add insert logic here

         return RedirectToAction("Index");
     }
     catch
     {
         return View();
     }
}

The action method that accepts a GET does not need to be modified; however, the action method that accepts a POST is incomplete.

In this example, I am assuming the Create View is a strongly-typed view of type System.Web.Mvc.ViewPage<DataLayer.Category>. In that case, the first thing I need to do is to change the type of the parameter that is used by the action method from FormCollection to Category. By doing this the framework does the model binding for me. If I leave the data type as FormCollection, I need to either loop through all of the objects on the form manually to update the model or use the UpdateModel method of the controller to update the model.

var category = new DataLayer.Category();
category.Name = collection["Name"];
...

It is much better to let the system try to bind the data to a strongly-typed object. When the system attempts to bind the data ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required