0

I have a cshtml page where I have datatable to display the data and a bootstrap pop up form via which I am doing insert and update operation. When the page loads, the data is displayed in datatable and if the user inserts new data, it is displayed after the successful insert operation.

I have having problem with UPDATE operation, after successful UPDATE operation also, the updated data is not shown in datatable. The data is displayed only after I do manual refresh of the page. It is working for INSERT operation, the new data is shown after INSERT operation.

My cshtml code::

@model models.FirmModel

@{
    ViewBag.Title = "OldRegistration";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<link rel="stylesheet" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css" />

<p>
    <a href="#" class="btn btn-primary title_header" data-toggle="modal" onclick="modalclick()" data-target="#insert_firm_modal">Reg</a>
</p>

@*============ modal for data insert ==================*@
<div class="modal fade" id="insert_firm_modal" role="dialog" aria-hidden="true" tabindex="-1" data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog modal-xlg" role="document">
        <div class="modal-content" id="insert_firm_modal_content">
            <form id="form_firm_data" enctype="multipart/form-data" method="POST">
                @Html.AntiForgeryToken()
               // my form ........               
                <div class="modal-footer">
                   <input type="submit" value="Submit" class="btn btn-success btn-sm" id="btn_submit" />
                   <input type="submit" value="Update" class="btn btn-success btn-sm" id="btn_edit" style="display:none;" />
                </div>
            </form>
        </div>
    </div>
</div>
@*===========================================================*@
@*======== data table data ==============*@
<div id="i_data_table">
    <table id="tblFirmData" class="table table-striped table-bordered dt-responsive nowrap title_header cell-border main_" width="100%" cellspacing="0" style="font-size: 14px; font-weight: 600;">
        <thead class="table-success">
            <tr>
                <th>Edit</th>
                // other data ....
            </tr>
        </thead>
        <tbody>
            @foreach (var item in ViewBag.Firm)
            {
                int status = item.FirmRegistrationStatus;
                int id = item.FirmId;
            <tr>
                <td>
                    <a href="#" class="btn btn-sm btn-danger" onclick="return getbyID(@id)">EDIT</a>
                </td>
            </tr>
            }
        </tbody>
    </table>
</div>
@*===========================================================*@
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/jquery-3.4.1.slim.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>

<script>
    $('#tblFirmData').DataTable({
        "rowCallback": function (row, data, index) {
            if (data[1] == "1") {
                $('td', row).css('background-color', '#D9EDF7');
            }
            else {
                $('td', row).css('background-color', '#A52A2A');
            }
        }
    });
    // =========== insert method ======================
    $('#btn_submit').click(function () {
        alert("submit button called...");
            // insert operation block
            $.ajax({
                type: "POST",
                url: "/FirmModels/OldRegistration",
                data: testModel, 
                contentType: false, 
                processData: false,
                dataType: 'json',
                success: function (response) {
                    $('#insert_firm_modal').modal('hide');
                    $('body').removeClass('modal-open');
                    $('.modal-backdrop').remove(); 
                    $('#form_firm_data').trigger("reset");
                    location.reload();
                },
                error: function (xhr, status, error) {
                    var errorMessage = xhr.status + ': ' + xhr.statusText
                    console.log('Error - ' + errorMessage);
                }
            })

            return false;
        });
    // =========== edit method ======================
    $('#btn_edit').click(function () {
        // update operation block
        testModel.append("firmModel_", JSON.stringify(firmModel_));        
        $.ajax({
            type: "POST",
            url: "/FirmModels/Update_OldRegistration_Firm",
            data: testModel, 
            contentType: false, 
            processData: false,
            dataType: 'json',
            success: function (response) {
                $('#insert_firm_modal').modal('hide');
                $('body').removeClass('modal-open');
                $('.modal-backdrop').remove();
                $('#form_firm_data').reset();
                location.reload();
            },
            error: function (xhr, status, error) {
                var errorMessage = xhr.status + ': ' + xhr.statusText
                alert('Error - ' + errorMessage);
            }
        })
        return false;
    });
    // =========== get method for UPDATE ======================
    function getbyID(EmpID) {
        $.ajax({
            url: "/FirmModels/GetByKey",
            data: { id: EmpID },
            type: "GET",
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            success: function (data) {
                // data mapping for update operation

                $('#insert_firm_modal').modal('show');
                $('#btn_edit').show();
                $('#btn_submit').hide();
            },
            error: function (errormessage) {
                alert(errormessage.responseText);
            }
        });
        return false;
    }
</script>

My controller method,

public ActionResult OldRegistration()
        {
            var firm_data = new FirmModel();
            var firm_ = (from z in db.FirmModels where z.Status == 10 select z).OrderByDescending(z => z.FirmId).ToList();
            ViewBag.Firm = firm_;
            return View(firm_data);
        }
        
[HttpPost]
        public JsonResult OldRegistration(string firmModel_)
        {
                if (ModelState.IsValid)
                {
                    FirmModel fm_ = new FirmModel();
                    var data = JsonConvert.DeserializeObject<FirmModel>(firmModel_);
                    // insert code block

                    db.FirmModels.Add(fm_);
                    db.SaveChanges();
                    return Json(new { success = true, responseText = "Your message successfuly sent!" }, JsonRequestBehavior.AllowGet);
                }
                return Json(new { success = false, responseText = "Error..." }, JsonRequestBehavior.AllowGet);

        }
[HttpPost]
        public JsonResult Update_OldRegistration_Firm(string firmModel_)
        {
                if (ModelState.IsValid)
                {
                    FirmModel fm_ = new FirmModel();
                    var data = JsonConvert.DeserializeObject<FirmModel>(firmModel_);
                    // update code block
                    db.Entry(fm_).State = EntityState.Modified;
                    db.SaveChanges();
                    return Json(new { success = true, responseText = "Your message successfuly sent!" }, JsonRequestBehavior.AllowGet);
                }
                return Json(new { success = false, responseText = "error..." }, JsonRequestBehavior.AllowGet);
        }

When the page loads OldRegistration() GET method is called and the ViewBag data populates the data table in view page, and for insert operation, new data is also populated in data table but when I do edit operation, even though the operation is successful the updated data is not showing in the datatable. I put alert code in $('#btn_edit').click(function() at ajax success block, the alert is shown but the data is not updated. The updated data is only displaying after I press F5, why is it so?

user4221591
  • 2,084
  • 7
  • 34
  • 68
  • 1
    I think you have to call "OldRegistration" Get method once you are done with the edit/ update in the JS, once data is updated successfully. – Avantha Siriwardana Dec 30 '21 at 08:29
  • @AvanthaSiriwardana How to call that? `public ActionResult OldRegistration()` and also it is not returning `json data` it is returning `view`. – user4221591 Dec 30 '21 at 08:35
  • I found something in here : [https://stackoverflow.com/questions/10178007/mvc3-redirect-to-action-after-ajax-call] Please have a look if it is a good fit for you – Avantha Siriwardana Dec 30 '21 at 10:27

0 Answers0