javascript - MVC : Ajax data not getting to Controller

标签 javascript c# jquery ajax asp.net-mvc

每个解决方案/类似问题都与 json 对象有关。我认为这个问题可能是由于使用html引起的。我还验证了数据在调用 ajax 之前不为空。

这是 Ajax

function SubmitSearch() {
    var type = $("#select_SearchType").val()
    var query = $("#input_Search").val()

    $.ajax({
        //url: "newSearch",
        url: '@Url.Action("newSearch", "Results")',
        type: 'POST',
        cache: false,
        dataType: "html",
        contentType: 'application/html; charset=utf-8',
        data: { type: type, query: query },
        success: function (ViewModel) {
            alert(ViewModel)
            $("#div_record").empty();
            $("#div_record").html(ViewModel)
        },
        error: function (ViewModel) {
            alert("error")
            $("#div_record").empty();
            $("#div_record").html(ViewModel)
        },
    });
}

并从操作中选择代码

    [HttpPost]
    public ActionResult newSearch(string type, string query)
    {
        switch (type)
        {
            case " ":
                response.errMess = "empty data, T:" + type + " Q:" + query;
                return PartialView("Record", response);
            default:
                response.errMess = "Error: mismatched fields, T:" + type + " Q:" + query;
                return PartialView("Record", response);
        }

类型和查询都是空的

最佳答案

您不需要使用contentType: 'application/html; charset=utf-8'。有一些方法。

首先,你必须使用这样的东西(直接将参数放在url中):

$.ajax({
    //url: "newSearch",
    url: '@Url.Action("newSearch", "Results")?type='+type+'&query='+query,
    type: 'POST',
    success: function (ViewModel) {
        alert(ViewModel)
        $("#div_record").empty();
        $("#div_record").html(ViewModel)
    },
    error: function (ViewModel) {
        alert("error")
        $("#div_record").empty();
        $("#div_record").html(ViewModel)
    },
});

第二。 您必须使用 data 将一些数据保存到服务器属性。

如果要返回PartialView,则无需使用dataType: "html"

类似这样的事情:

$.ajax({
    //url: "newSearch",
    url: '@Url.Action("newSearch", "Results")',
    type: 'POST',
    cache: false,
    data: { type: type, query: query },
    success: function (ViewModel) {
        alert(ViewModel)
        $("#div_record").empty();
        $("#div_record").html(ViewModel)
    },
    error: function (ViewModel) {
        alert("error")
        $("#div_record").empty();
        $("#div_record").html(ViewModel)
    },
});

关于javascript - MVC : Ajax data not getting to Controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41151309/

相关文章:

javascript - 我不能在 &lt;script&gt; 中使用 <h1>

java - jQuery 或 JavaScript 中的 JSTL

C# XNA : Looking for a function like MathHelper. 钳位

javascript - Colorbox的tabindex =“-1”属性可防止在表单字段上进行焦点和键入

javascript - 处理缓慢的回调函数

javascript - 使用 JQuery 选择第二个前一个元素

javascript - 处理并保持 node.js/express session

c# - 停止线程、ManualResetEvent、volatile boolean 或 cancellationToken

C#:我希望单词的每个字母都以新行开头

jQuery UI 对话框按钮图标