Skip to Main Content
ASP.NET 4 24-Hour Trainer
book

ASP.NET 4 24-Hour Trainer

by Toi B. Wright
July 2010
Beginner content levelBeginner
552 pages
10h 14m
English
Wrox
Content preview from ASP.NET 4 24-Hour Trainer

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

ASP.NET 4 24-Hour Trainer

ASP.NET 4 24-Hour Trainer

Toi B. Wright
ASP.NET 4 Unleashed

ASP.NET 4 Unleashed

Stephen Walther, Kevin Hoffman, Nate Dudek

Publisher Resources

ISBN: 9780470596913Purchase bookExamplesErrata