0

I'm using bootstrap-table library to create a table in my ASP.net MVC view. Whenever the user double click on the table row, requirement is to pick the table row data and transfer it to a model popup.

I'm able to pick the row column values using row[] array in Javascript but I'm not able to transfer it to my controller through Ajax.

Please find below my code snippet:-

<html lang="en-AU">
<head>
<script>

$(document).ready(function () {

$('#tblID').bootstrapTable({ locale: 'en-US' }).on('click-row.bs.table', function (e, row, $element) {

var param = row[2]; //fetching 3rd column value

$.ajax({
      type: "GET",
      url: '@Url.Action("_SampleAction", "SampleController")',
      data: '{ID: "' + param + '" }',
      datatype: "json",
      success: function (result) {
      $('#myModelContent').html(result);
      $("#myModal").modal('show');
      },
      error: function (req, status, error) {
           alert("Error!Occured");
      }
    });

});

});

</script>
</head>

<body>

<table id="tblID" class="table table-hover" data-search="true" data-show-columns="true" data-mobile-responsive="true" data-striped="true" data-toggle="table" data-sort-name="Salary" data-sort-order="desc" data-pagination="true" data-smart-display="true" data-filter-control="true" data-show-export="true" data-click-to-select="true" data-page-list="[5, 10, 25, 50, 100, ALL]" data-export-options='{"fileName": "ActiveList","ignoreColumn": ["state"]}'>

    <thead>
            <tr>
                @foreach (DataColumn col in Model.Details.Columns)
                {
                    <th class="TableRowHeader" data-sortable="true" data-filter-control="Select">@col.ColumnName</th>
                }
            </tr>
    </thead>
    <tbody>
            @foreach (DataRow row in Model.MonitorDetails.Rows)
            {
                <tr>
                    @foreach (DataColumn col in Model.MonitorDetails.Columns)
                    {
            <td class="TableBody">@row[col.ColumnName]</td>
            }
                </tr>
            }
        </tbody>
</table>

    <div class="modal fade" tabindex="-1" id="myModal" data-keyboard="false" data-backdrop="static">
        <div class="modal-dialog">
            <div class="modal-content" style="width: auto;">
                <div id='myModalContent'></div>
            </div>
        </div>
    </div>

</body>
</html>

SampleController:-

public ActionResult _SampleAction(string ID)
    {
        MyModel objMyModel  = new MyModel ();
        objMyModel.ID = ID;
        try
        {
            return PartialView("_SampleAction", objMyModel);

        }
        catch (Exception ex)
        {
            return RedirectToAction("Index", "Error");
        }
    }

But I'm receiving parameter ID as null and Ajax call fails.

Can anyone please guide me on how to achieve this?

Thanks in advance.

ASHISH_TECHIT
  • 107
  • 4
  • 16
  • 1
    `data: '{ID: "' + param + '" }'` is wrong, you need to use `data: { ID: param }` instead. MVC action method is smart enough to identify passed JSON object as its argument. – Tetsuya Yamamoto Aug 15 '18 at 05:32
  • @TetsuyaYamamoto thanks that refactoring solved the issue. – ASHISH_TECHIT Aug 15 '18 at 06:33
  • Also you need to change your way to redirect into error page because AJAX is not intended to perform `RedirectToAction` (see the answer for better approach). – Tetsuya Yamamoto Aug 15 '18 at 06:36

1 Answers1

0

AJAX callback is not intended to perform redirection to another action method (also assigning data parameter with string concatenation like data: '{ID: "' + param + '" }' is definitely wrong). Try configure AJAX callback to find out if error message exists like this:

$.ajax({
      type: "GET",
      url: '@Url.Action("_SampleAction", "SampleController")',
      data: { ID: param }, // proper way to pass string to controller with AJAX

      // other AJAX settings

      success: function (result) {
          if (result.message == undefined) {
              $('#myModelContent').html(result);
              $("#myModal").modal('show');
          } else {
              // set redirection here instead of using RedirectToAction from controller
              window.location.href = result.url;
          }
      },
      error: function (req, status, error) {
           alert("Error occurred");
      }
    });
});

And the controller action should return JSON data when exception occurs, as given below:

public ActionResult _SampleAction(string ID)
{
    MyModel objMyModel = new MyModel();
    objMyModel.ID = ID;
    try
    {
        // do something

        return PartialView("_SampleAction", objMyModel);
    }
    catch (Exception ex)
    {
        return Json(new { url = Url.Action("Index", "Error"), message = ex.Message }, JsonRequestBehavior.AllowGet);
    }
}

Related issue:

RedirectToAction not working after successful jquery ajax post?

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61