Josh G
Josh G

Reputation: 53

MVC: Ajax data not getting to Controller

Every solution/similiar question has to do with json objects. I think the problem may be caused by using html. I have also verified the data is not empty before it hits the ajax call.

Here is the 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)
        },
    });
}

And selected code from the 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);
        }

type and query both come in empty

Upvotes: 2

Views: 919

Answers (1)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48437

You do not need to use contentType: 'application/html; charset=utf-8'. There are some methods.

First, you have to use something like this (put parameters directly in 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)
    },
});

Second. You have to save some data to the server using data property.

If you want to return PartialView, there is no need to use dataType: "html"

Something like this:

$.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)
    },
});

Upvotes: 2

Related Questions