DEV Community

Sardar Mudassar Ali Khan
Sardar Mudassar Ali Khan

Posted on

Updatemodel function in MVC with example

In the context of the Model-View-Controller (MVC) design pattern, the UpdateModel function is used to update the model object with the values submitted from a form or user input. It is typically used in the controller to bind the incoming data to the model.

Here's an example of how the UpdateModel function can be used in an MVC application:

Let's assume we have a simple model called Person with two properties: Name and Age.

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

In the controller, you might have an action method to handle a form submission:

public class PersonController : Controller
{
    [HttpPost]
    public ActionResult Edit(int id, FormCollection form)
    {
        // Get the person object from the database using the provided ID
        var person = GetPersonById(id);

        // Update the model object with the form values using UpdateModel
        UpdateModel(person, form);

        // At this point, the person object will have its properties updated
        // with the values submitted from the form.

        // Perform any necessary operations (e.g., saving to the database)

        // Redirect to a different action or view
        return RedirectToAction("Details", new { id = person.Id });
    }
}
Enter fullscreen mode Exit fullscreen mode

In the above example, the Edit action method receives the form values as a FormCollection object, which contains all the submitted data. The UpdateModel function is called with the person object and the form collection.

The UpdateModel function will match the keys in the form collection with the properties in the person object based on their names and update the corresponding property values. This binding process is performed automatically by the MVC framework.

After the UpdateModel function call, the person object will have its properties updated with the submitted values. You can then perform any necessary operations (e.g., saving the changes to the database) and redirect to a different action or view.

Note: In newer versions of ASP.NET MVC, the UpdateModel method has been deprecated in favor of the TryUpdateModel or TryUpdateModelAsync methods, which provide better control over the binding process and protect against over-posting attacks.

Top comments (0)