Part 12 - Creating a view to insert data using mvc

Leave a Comment
we will discuss, creating a view to insert a new employee into the database table tblEmployee

We want to present the end user with a form as shown in the image below

Copy and paste the following "Create" action method, in EmployeeController class. 
public ActionResult Create()
    return View();

Please note that, the method is decorated with "HttpGet" attribute. This makes this action method to respond only to the "GET" request. 

Now let's add a "Create" view. To do this, right click on the "Create" action method and select "Add View" from the context menu. Set
1. View name = "Create"
2. View engine = "Razor"
3. Select "Create Strongly-typed view" checkbox
4. Select "Employee" class, from "Model class" dropdownlist
5. Scaffold Template = Create
6. Click "Add" button

At this point "Create.cshtml" view will be added in "Employee" folder. If you have the following "Scripts" section at the bottom of the view, please delete it. We will discuss about sections and scripts in a later video session.
@section Scripts {

Run the application and navigate to the following URL

Click on "Create New" link. You will be naviaged to the following URL

A form with textboxes to add a new employee is rendered. For employee "Gender" it is ideal to have a dropdownlist instead of a text box. To achieve this, REPLACE THE FOLLOWING LINE
@Html.EditorFor(model => model.Gender)

@Html.DropDownList("Gender"new List<SelectListItem>
new SelectListItem { Text = "Male", Value="Male" },
new SelectListItem { Text = "Female", Value="Female" }
}, "Select Gender")

Run the application and notice that, a dropdownlist is now displayed for "Gender".

If you click on "Create" button, you will get an error message stating - The resource cannot be found. This is because we don't have the "Create" controller action method that can handle HTTPPost request.


Post a Comment

Note: only a member of this blog may post a comment.