Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Part 17 - Editing a model in mvc

Suggested Videos 
Part 14 - Mapping asp.net request data to controller action simple parameter types
Part 15 - Updatemodel function in MVC
Part 16 - Difference between UpdateModel and TryUpdateModel



In this video we will discuss editing a model in mvc. Please watch Part 16, before proceeding.



Step 1: Copy and paste the following "Edit" controller action method in "EmployeeController.cs" file.
[HttpGet]
public ActionResult Edit(int id)
{
    EmployeeBusinessLayer employeeBusinessLayer = 
           new EmployeeBusinessLayer();
    Employee employee = 
           employeeBusinessLayer.Employees.Single(emp => emp.ID == id);
            
    return View(employee);
}

Please note:
1. This method is decorated with [HttpGet] attribute. So this method only responds to HTTP get request when editing data.
2. The "Edit" action method also receives "id" of the employee that is being edited. This "id" is used to retrieve the employee details.
3. The employee object is passed to the view

Step 2: Add "Edit" view
a) Right click on the "Edit" controller action method, and select "Add view" from the context menu
b) Set
    View name = Edit
    View engine = Razor
    Select "Create a strongly-typed view" check box
    Model class = "Employee"
    Scaffold template = "Edit"
    Finally click "Add" button
c) This should add "Edit.cshtml" to "Employee" folder in "Views" foolder
d) Delete the following scripts section that is present at the bottom of "Edit.cshtml" view
@section Scripts 
{
    @Scripts.Render("~/bundles/jqueryval")
}

Run the application and navigate to http://localhost/MVCDemo/Employee/Index. This page should list all the employees. Click on "Edit" link. The "Edit" page should display the details of the "Employee" being edited. Notice that, by default "textboxes" are used for editing. It is ideal to have a dropdownlist for gender rather than a textbox. To achieve this. make the following changes to "Edit.cshtml"

REPLACE THE FOLLOWING CODE
@Html.EditorFor(model => model.Gender)
@Html.ValidationMessageFor(model => model.Gender)

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

Run the application. Edit an employee, and notice that a DropDownList is used for gender as expected. Post the form by clicking on "Save" button. We will get an error stating - The resource cannot be found. We will discuss fixing this in our next video.

13 comments:

  1. Hi Venkat,

    I am getting this error after editing. The records saves but when it redirects to the view I am getting this error.
    The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(Int32)' in 'MVC4Demo.Controllers.EmployeeController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
    Parameter name: parameters

    please help me.

    Thanks
    Kumar

    ReplyDelete
    Replies
    1. Can you let me know to which action method or view, are you redirecting.

      Delete
    2. Hi Rakesh,

      I have the same error but why I have changed the name of my id parameter on

      public ActionResult Edit(int id)

      I used employeeId. To solve the problem check your Index view on Edit link, you must to see a thing how this

      @Html.ActionLink("Edit", "Edit", new { id=item.ID })

      where the lower "id" is the name of the parameter in Edit function.

      I hope to help you.

      Regards
      Luca Jonathan Panetta

      Delete
    3. Hey Go to the IndexPage View of your ActionLink Edit then pass Id Parameter

      Delete
  2. Hi Venkat,
    Your tutorials are very useful.I am using aspx engine instead of Razor. I am getting the following error. Plz help.
    Sequence contains no elements.
    [HttpGet]
    public ActionResult Edit(int id)
    {
    MvcCRUDcontext MvcContext = new MvcCRUDcontext();
    //Error in this statement MvcCRUD mvc = MvcContext.MvcCRUDs.Single(x => x.Id == id);
    return View(mvc);
    }

    ReplyDelete
    Replies
    1. Either the value for the parameter id would come as null or there wont be data in the table for the id passing

      Delete
  3. Hi Venkat,

    I am not able to bind the selected value back into the edit dropdown list. Ex: If the employee gender is male and we want to edit it to female. It is not populating as male in the edit page. It displays "select gender" instead. Can you please give me some hints on where I am going wrong.

    ReplyDelete
    Replies
    1. Trim your value while selecting from database.

      Delete
    2. This comment has been removed by the author.

      Delete
  4. In edit mode, 'Select Gender' is displayed as selected in 'Gender' drop down instead of specified records gender value..
    Can you suggest me how to solve this..
    I used following code from this blog..
    @Html.DropDownList("Gender", new List
    {
    new SelectListItem { Text = "Male", Value="Male" },
    new SelectListItem { Text = "Female", Value="Female" }
    }, "Select Gender")
    @Html.ValidationMessageFor(model => model.Gender)

    ReplyDelete
  5. replace "Select Gender" with Model.Gender

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. i have a problem that during click the edit option my edit view take all the data from Db except dropdown they still remain on select gender option please help me out

    ReplyDelete

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.