MVC:Ajax数据无法访问Controller

时间:2016-12-14 20:08:28

标签: 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)
        },
    });
}

从Action

中选择代码
    [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);
        }

类型和查询都是空的

1 个答案:

答案 0 :(得分:2)

您无需使用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)
    },
});