0

I use the Datatables.mvc for Crud operations in MVC. for Edit, I'm sending ids to An action to rendering _EditPartial for editing. in controller check's

If(Request.IsAjaxRequest)
// go to partialview...

but that it is always false! I checked every jquery libraries versions such as validate, unobtrusive-ajax and ... but still not working. I checked the headers of the request and there is no

X-Requested-With

Cshtml:

var assetListVM;
    $(function () {
        assetListVM = {
            dt: null,

            init: function () {
                dt = $('#assets-data-table').DataTable({
                    language: {
                        url: '//cdn.datatables.net/plug-ins/1.10.19/i18n/Persian.json'
                    },
                    "serverSide": true,
                    "processing": true,
                    "ajax": {
                              "url": "@Url.Action("GetDepartments", "BaseInfo")",

                    },
                    "columns": [
                        { "title": "نام دپارتمان", "data": "deptname", "searchable": true },
                        { "title": "کد دپارتمان", "data": "deptCode", "searchable": true },
                        { "title": "عکس", "data": "deptPic", "searchable": false, "sortable": false, },

                        {   
                            "title": "actions",
                            "data": "deptId",
                            "searchable": false,
                            "sortable": false,
                            "render": function (data, type, full, meta) {
                                return '<a href="@Url.Action("EditDepartment", "baseinfo")?id=' + data + '" class="btn btn-app"><i class="fa fa-edit"></i> Edit</a> <a href="@Url.Action("DetailsDepartment", "BaseInfo")?id=' + data + '" class="btn btn-app"><i class="fa fa-file-text"></i> Details</a> <a href="@Url.Action("DeleteDepartments", "BaseInfo")?id=' + data + '" class="btn btn-app"><i class="fa fa-trash"></i> Delete</a>';
                            }
                        }
                    ],
                    "lengthMenu": [[10, 25, 50, 100], [10, 25, 50, 100]],
                });
            },

            refresh: function () {
                dt.ajax.reload();
            }
        }

I copy these codes from a sample, in that sample everything work's fine and has X-Requested-With. what should I do? thanks.

Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
Reza sixxx
  • 15
  • 1
  • 8
  • Have you included `jquery.unobtrusive-ajax.js` (or minified `jquery.unobtrusive-ajax.min.js`) file in the view? Also check if ` ` is available in configuration file. – Tetsuya Yamamoto Aug 07 '18 at 07:11
  • @TetsuyaYamamoto yes i have. all js file are included and in web config , add key has been added , I've been work on this for 2 day's but not figure it out! – Reza sixxx Aug 07 '18 at 08:39
  • jQuery sets `X-Requested-With` to `XMLHttpRequest` for AJAX callback by default. If the header is missing, possibly you should add `ActionFilterAttribute` which sets both `HttpContext.Request.Headers["X-Requested-With"]` and `IsAjaxRequest` simultaneously. – Tetsuya Yamamoto Aug 07 '18 at 09:20
  • @TetsuyaYamamoto , do you have any example or implementation this attribute? – Reza sixxx Aug 07 '18 at 10:33

1 Answers1

0

controller

public class HomeController : Controller
{
    //this is the post controller that gets called
    //from ajax when the button pass data clicked
    [HttpPost]
    public ActionResult reservation_step_1(string id)
    {
        //I am passing in a string with name id that matches the
        //data: { 'id': myId }, in the view

        //this is true because it is called with ajax, else it would be false
        if (Request.IsAjaxRequest())
        {
            //!!!
            var thisIsAjaxRequest = true;
        }

        string val = id;

        return RedirectToAction("reservation_step_2", "Home", new { val = val });
    }

    //my controller action name, yours is different
    public ActionResult Tut118()
    {
        //kudos to https://stackoverflow.com/questions/51728689/value-not-passing-from-view-to-controller-using-ajax/51735309#51735309
        return View();
    }

view

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Tut118</title>
    <!-- I need to include script for jQuery  -->
    <script src="~/Scripts/jquery-1.12.4.min.js"></script>
    <script type="text/javascript">
        $(function () {
            //trigger on when button is clicked
            $("#theButton").click(function () {
                //kudos to https://stackoverflow.com/questions/5450104/using-jquery-to-get-all-checked-checkboxes-with-a-certain-class-name

                //set myId to the selected checkbox attribute data-id
                //so if first box checked=1, second=2, third=3
                var myId = $('.slectOne:checkbox:checked').attr("data-id");
                $.ajax({
                    type: "Post",
                    //calling specific method
                    url: '@Url.Action("reservation_step_1", "Home")',
                    //passing data
                    data: { 'id': myId },
                    //type of data json
                    dataType: 'json',
                    success: function (data) {
                        //on return, go through each return record
                        //and append to dropdown list
                        //, see jQuery append
                        $.each(data, function (i, anObj) {
                            $("#Asentamientos").append($('<option>').text(anObj.Text).attr('value', anObj.Value));
                        });
                    }
                });
            })

            //this I took from below link
            //what it does is to allow only one selection
            //between each checkbox
            //kudos to https://stackoverflow.com/questions/9709209/html-select-only-one-checkbox-in-a-group
            // the selector will match all input controls of type :checkbox
            // and attach a click event handler
            $("input:checkbox").on('click', function () {
                // in the handler, 'this' refers to the box clicked on
                var $box = $(this);
                if ($box.is(":checked")) {
                    // the name of the box is retrieved using the .attr() method
                    // as it is assumed and expected to be immutable
                    var group = "input:checkbox[name='" + $box.attr("name") + "']";
                    // the checked state of the group/box on the other hand will change
                    // and the current value is retrieved using .prop() method
                    $(group).prop("checked", false);
                    $box.prop("checked", true);
                } else {
                    $box.prop("checked", false);
                }
            });
        })
    </script>
</head>
<body>
    <div>
        <!-- These are the checkboxes and button -->
        <h3>CheckBoxes</h3>
        <label>
            <input data-id="1" type="checkbox" class="slectOne" value="1" name="fooby[1][]" />CheckBox1
        </label>
        <label>
            <input data-id="2" type="checkbox" class="slectOne" value="1" name="fooby[1][]" />CheckBox2
        </label>
        <label>
            <input data-id="3" type="checkbox" class="slectOne" value="1" name="fooby[1][]" />CheckBox3
        </label>
    </div>
    <input type="button" id="theButton" value="PassData" />
</body>
</html>
kblau
  • 2,094
  • 1
  • 8
  • 20