Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

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.

19 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
    4. yes, I got the same issue while working on this and solved the issue as per above comment. Thanks guys for the post.

      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
    2. Im having same issue while using following code line

      Employee employee = employeeBusinessLayer.employees.Single(x => x.EmployeeId == id);

      I'm having Error : Sequence contains more than one matching element

      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
  8. Sequence contains no matching element

    Plz help me...

    ReplyDelete
  9. change this
    @Html.ActionLink("Edit", "Edit", new { id=item.EmpId })

    and if there is any problem with the code simply copy paste the tutorials code then make some change according to your field and run
    the program it will work .
    in my case i have followed this is it is working as expected.

    ReplyDelete
  10. Hi Venkat,

    i am getting sequence contains more than one matching element error page clicking on edit link.

    Please help me to resolve this issue.

    ReplyDelete
  11. I'm getting an error (see below) when I try to implement this. I had it working but changed something and now I can't seem to get it to show the Edit View. Can someone point me in the right direction? I can Delete and Create, just can't seem to Edit. Oh you might notice that the Model is of class Quote; I've just have a simple table with QuoteID, QuotePerson, QuoteText. No logic has changed from the video just the BusinessLayer Class.

    --------------------------------------------------
    Error when opening the Edit View:
    The model item passed into the dictionary is of type 'BusinessLayer.Quote', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[BusinessLayer.Quote]'.

    -----------------------------------------------------
    QuotesController Class: (Edit Method)
    [HttpGet]
    public ActionResult Edit(int id)
    {
    QuoteBusinessLayer quoteBusinessLayer =
    new QuoteBusinessLayer();

    Quote quote = quoteBusinessLayer.Quotes.Single(q => q.QuoteID == id);
    return View(quote);
    }

    ---------------------------------------------------------
    View file:
    @model BusinessLayer.Quote
    ....

    @Html.DisplayNameFor(model => model.QuoteText)



    @Html.DisplayFor(model => model.QuoteText)



    @Html.DisplayNameFor(model => model.QuotePerson)



    @Html.DisplayFor(model => model.QuotePerson)

    .....

    ReplyDelete

It would be great if you can help share these free resources