ASP.NET MVC > Entity Framework

Update record into database in ASP.NET MVC

How to update a record into the database in ASP.NET MVC?


To update a record into the database, we can use the same scaffolding template we were talking about in Insert or List topics.

NOTE

In order to understand this completely, it is recommended to read How to insert ….. topic as in this post we have cut short few topics that are repetitive in nature.

Here is the action methods of the controller

CONTROLLER ACTION METHODS

       // GET: PersonalDetails/Edit/5
       public ActionResult Edit(int? id)
       {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            PersonalDetail personalDetail = db.PersonalDetails.Find(id);
            if (personalDetail == null)
            {
                return HttpNotFound();
            }
            return View(personalDetail);
        }

        // POST: PersonalDetails/Edit/5
        // To protect from overposting attacks, please enable the specific
properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include =
"AutoId,FirstName,LastName,Age,Active")] PersonalDetail personalDetail)
        {
            if (ModelState.IsValid)
            {
                db.Entry(personalDetail).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(personalDetail);
        }

In the first action method, id parameter is checked for null, if null it returns bad request otherwise record having primary key value as id is found and returned to the Edit view.

EDIT VIEW CODE

@model WebApplication1.Models.PersonalDetail

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm())
{
        @Html.AntiForgeryToken()
        <div class="form-horizontal">
        <h4>PersonalDetail</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.AutoId)
        <div class="form-group">
            @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class =
"control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new
{ @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.FirstName, "", new {
@class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class =
"control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LastName, new { htmlAttributes = new
{ @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.LastName, "", new { @class
= "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Age, htmlAttributes: new { @class =
"control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Age, new { htmlAttributes = new {
@class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Age, "", new { @class =
"text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Active, htmlAttributes: new { @class =
"control-label col-md-2" })
            <div class="col-md-10">
                <div class="checkbox">
                    @Html.EditorFor(model => model.Active)
                    @Html.ValidationMessageFor(model => model.Active, "", new {
@class = "text-danger" })
                </div>
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
    }
    
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>

    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
    }

Above view is almost similar to the Create view except @Html.HiddenFor that renders a hidden element with current primary key value used to find and update the record.

Clicking on Edit link on the list page (Index) brings us to Edit page for corresponding record.

Clicking on Save button fires 2nd Edit action method that checks for validation errors in the Model, if OK then makes the state of that record to Modified and calls SaveChanges() method to save the record into data. If the model is not valid, it redirects on the same Edit page and shows validation errors.

 Views: 6678 | Post Order: 102



Write for us