views:

80

answers:

2

Hi there,

Can anyone tell help me understand the new CRUD scaffolding that is included with MVC 2?

Let me explain, for example below you have 2 Create Actions...

Now i presume that if i have the form "Post to itself" then the second with Attribute POST is executed - IS THIS CORRECT? so a form within a view that when Submitted submits to itself??, but when would the standard Create be called i.e. the 1 that has the // GET comment at the start.

I do understand that the default action is Index hence this would be normally called when my page is displayed but i can't seem to find any info on Create action. I presume its a magic word hence it needs to be called Create ???

    // GET: /Customer/Create

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

    //
    // POST: /Customer/Create

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(FormCollection collection)
    {
        try
        {
            // TODO: Add insert logic here

            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }
+1  A: 

There's nothing magic about the name 'Create'. Any normal link to the create action (say, one created by a Url.Action("Create") call) would result in a page request to the non-POST (GET) version. A form on the GET version of the page with method="POST" will result in the POST version getting called. You can use this same pattern for actions with other names.

nullptr
+3  A: 

Create() (no attributes) is called when the page is first loaded. ie. The empty form is displayed to the user

Create(FormCollection) (AcceptVerbs attribute) is called when the form is submitted with data.

Both can use the same ASPX as a view.

Richard Szalay
Hi, but i thought Index is called when the page is first loaded, this is the default action for the controller? ...
mark smith
In the default configuration, `Index` is called when there is no action specification in the url (ie. `/Customer`). The first `Create` method in your sample is called when `/Customer/Create` is called initially (ie. HTTP GET), and the second `Create` is called when the data is posted from the form (ie. HTTP POST)
Richard Szalay
Richard put it rather nicely. One thing to note - this is no different in version 2 then it was in first version.
mare