About the Default Create Action Methods in MVC Controller

March 03, 2014 , , , 0 Comments

Earlier article was about the default index action of the controller, which in other words used to list the records from the database created in MVC application. Except this list (Index) action, all other actions are of two types i.e. Get and Post, having particular motive in the programming.

According to name, Get method is used to get a particular model and return to the view that will show that model. The below code will return the blank model of Student class (Controller). User will enter particular information in the textboxes shown on the form and click on submit button.

// GET: /Student/Create
public ActionResult Create()
return View();

After clicking on the submit button, compiler goes to the post method of the same action i.e. Post Create action, as written below:

public ActionResult Create(Student student)
if (ModelState.IsValid)
return RedirectToAction("Index");
return View(student);

The first two line of this code are attributes used to tell the compiler about this method i.e. this is post method and validates fields on submit method. The parameter is of type student means the view is of Student type (having all the fields of Student class) as shown some lines of the create view:

@model MvcApplication1.Models.Student
@using (Html.BeginForm()) {
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)

This view is strongly typed view because of the first line and have all the fields of student class (only name is shown here, remaining are something like this).

So, turn back on our previous discussion that was about the post Create action. This action will then check the model is valid or not (Validation). If valid then it will add this new student in the student table and then save the changes to the database. If not it will return to the same page with the errors generated.

The last line will return to the same action i.e. Create with the model passed as parameter and of course validation errors, you can check this to not enter some fields in the form and submit the data. The next will be to edit the student.

Subhash Sharma

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard. Google