-1

I'm trying to set up what should be a very simple call from an MVC page to a controller using JavaScript. This is my Controller:

Imports System.Web.Mvc

Namespace Controllers
    Public Class DataController
        Inherits Controller

        Function Index() As ActionResult
            Return View()
        End Function

        <HttpPost>
        Function SaveData(payload As String) As String
            If payload IsNot Nothing AndAlso payload.Length > 0 Then
                Return "Good"
            Else
                Return "Bad"
            End If
        End Function

    End Class
End Namespace

this is my View (Index.vbhtml):

@Code
    ViewData("Title") = "Index"
End Code

<h2>Index</h2>

@Code
    Html.BeginForm()
    @:<a href="#" onclick="SaveData();">Save Data</a>
    Html.EndForm()
End Code

and this is my JavaScript (included via the _layout.vbhtml file):

function SaveData() {

    var payload = "TEST_DATA_GOES_HERE";

    // Calls controller correctly but data is null
    $.ajax({
        url: "/Data/SaveData",
        type: "POST",
        processData: false,
        dataType: String,
        data: { payload: payload }
    })
    .done(function () { alert('Application saved.'); })
    .fail(function () { alert('Application failed to save.'); });

    // Returns a 500 error
    $.post("/Data/SaveData", { Payload: payload }, function (data) { alert('Application saved. ' + data); }, "String");

    // Calls controller correctly but data is null
    $.post("/Data/SaveData", payload, function () { alert('Application saved.' + data); }, "String");
}

Everything connects up nicely when debugging but the payload variable arrives as Nothing in the SaveData function. I've tried using $.post but with similar problems and all the references I've found to using either method simply assume that it will work first time without error and don't have any troubleshooting tips.

How do you configure the $.ajax or $.post functions to correctly call a controller and pass a simple string?

4
  • 1
    try changing { Payload: payload } to { payload: payload }. Commented Nov 17, 2014 at 15:48
  • That's curious it makes no difference to the $.ajax call but the first $.post now gets the data to the controller. Thanks. Commented Nov 17, 2014 at 15:51
  • 1
    Shouldn't dataType be "text" instead of String? Commented Nov 17, 2014 at 15:54
  • Doesn't seem to make any difference... Commented Nov 17, 2014 at 16:06

2 Answers 2

1

You need to set processData to true as you are sending an object which will need to be converted to a querystring.

From the API:

ProcessData
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.

http://api.jquery.com/jQuery.ajax/

Sign up to request clarification or add additional context in comments.

4 Comments

Excellent. I changed it to true and the data now arrives at the controller but the .fail function is always called. What needs to be returned from the controller for it to indicate a success?
The fail handler being hit indicates that the server response was anything other than 200 OK. You should debug that server side. Assuming you're using Visual Studio you can step through the code to find the exact line the error happened. Alternatively you can check the reponse code in the network section of the Console.
So if I need to send a very long string, with a bunch of non url encoded characters, I should set this to false? Right? What else needs to be set?
In general use you would very rarely need to amend processData. I would leave it omitted to use the default (which is true).
0

Thanks to the answer form Rory this is what I ended up with:

Controller:

<HttpPost>
Function SaveData(payload As String) As Boolean
    If payload IsNot Nothing AndAlso payload.Length > 0 Then
        Return True
    Else
        Return False
    End If
End Function

JavaScript:

function SaveData() {

    var payload = "TEST_DATA_GOES_HERE";

    // Calls controller correctly but data is null
    $.ajax({
        url: "/Data/SaveData/",
        type: "POST",
        data: { payload: payload }
    })
    .done(function () { alert('Application saved.'); })
    .fail(function () { alert('Application failed to save.'); });

}

Note that the $.ajax call doesn't have the processData or dataType elements and that the name of the variable matches the case of the parameter.

However what I found out is that my real problem was actually caused by passing XML as a string in this call. The XML cannot be simply passed as is in the query string. If you do that it arrives as null most likely because the MVC model binder can't process the resulting bad querystring.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.