【问题标题】:send ajax request to contoller is not working向控制器发送 ajax 请求不起作用
【发布时间】:2018-08-07 07:07:59
【问题描述】:

我在 MVC 中使用 Datatables.mvc 进行 Crud 操作。 对于编辑,我将 ids 发送到渲染 _EditPartial 以进行编辑的操作。 在控制器检查中

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

但它总是错误的! 我检查了每个 jquery 库版本,例如 validate、uno​​btrusive-ajax 和......但仍然无法正常工作。 我检查了请求的标头,没有

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();
            }
        }

我从一个示例中复制了这些代码,在该示例中一切正常,并且具有 X-Requested-With。 我该怎么办?谢谢。

【问题讨论】:

  • 您是否在视图中包含了jquery.unobtrusive-ajax.js(或缩小的jquery.unobtrusive-ajax.min.js)文件?还要检查&lt;add key="UnobtrusiveJavaScriptEnabled" value="true"/&gt; 是否在配置文件中可用。
  • @TetsuyaYamamoto 是的,我有。所有 js 文件都包含在 web 配置中,添加密钥已添加,我已经为此工作了 2 天,但没有弄清楚!
  • jQuery 默认将 X-Requested-With 设置为 XMLHttpRequest 用于 AJAX 回调。如果标题丢失,您可能应该添加ActionFilterAttribute,它同时设置HttpContext.Request.Headers["X-Requested-With"]IsAjaxRequest
  • @TetsuyaYamamoto ,你有这个属性的例子或实现吗?

标签: asp.net-mvc datatables asp.net-ajax


【解决方案1】:

控制器

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();
    }

查看

@{
    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>

【讨论】:

    猜你喜欢
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-04
    • 1970-01-01
    • 2021-04-08
    • 2021-08-09
    相关资源
    最近更新 更多