DEV Community

Sardar Mudassar Ali Khan
Sardar Mudassar Ali Khan

Posted on

Editing a model in much with example

To edit a model in MVC, you typically follow these steps:

  1. Retrieve the existing model data.
  2. Display the edit form populated with the current model values.
  3. Accept the form submission and update the model with the edited values.
  4. Save the updated model data.

Here's an example of how to edit a model in MVC:

  1. Retrieve the existing model data:
public class PersonController : Controller
{
    public ActionResult Edit(int id)
    {
        // Retrieve the existing person object from the database using the provided ID
        var person = GetPersonById(id);

        // Pass the person object to the view
        return View(person);
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. Display the edit form: Create a view called "Edit.cshtml" and populate it with the HTML form elements to display the person's properties. Use the Razor syntax to bind the form fields to the corresponding properties of the model.
@model Person

@using (Html.BeginForm("Edit", "Person", FormMethod.Post))
{
    @Html.HiddenFor(m => m.Id)

    <label for="Name">Name:</label>
    @Html.TextBoxFor(m => m.Name)

    <label for="Age">Age:</label>
    @Html.TextBoxFor(m => m.Age)

    <input type="submit" value="Save" />
}
Enter fullscreen mode Exit fullscreen mode
  1. Accept the form submission and update the model:
public class PersonController : Controller
{
    [HttpPost]
    public ActionResult Edit(Person updatedPerson)
    {
        if (ModelState.IsValid)
        {
            // Update the model with the edited values
            var person = GetPersonById(updatedPerson.Id);
            person.Name = updatedPerson.Name;
            person.Age = updatedPerson.Age;

            // Save the updated model data (e.g., update the database)

            return RedirectToAction("Details", new { id = person.Id });
        }
        else
        {
            // If there are validation errors, redisplay the edit form
            return View(updatedPerson);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. Save the updated model data: In the Edit action method, you retrieve the existing person object by its ID. Then, you update the person's properties with the edited values submitted through the form. Finally, you save the updated model data (e.g., update the database) and redirect to a different action or view, such as the person's details page.

This example assumes the existence of a GetPersonById method that retrieves a person object from the database based on the provided ID.

Note: Remember to handle validation errors appropriately. In this example, if there are validation errors (ModelState.IsValid is false), you redisplay the edit form, allowing the user to correct the errors.

Top comments (0)