2

I cannot seem to do this very simple task of passing a string to a controller when a button is pressed. The data received, is always null. Can someone tell me what I'm doing wrong?

Form:

<form>
    <div class="form-group">
        <label for="ProcessName" class="control-control">Process Name</label>
        <input id="ProcessName" class="form-control" placeholder="Choose process name">
        <small id="subtitle" class="form-text text-muted">Text under input field.</small>
    </div>
    <button type="submit" class="btn btn-primary" id="addElement">Submit</button>
</form>

Javascript:

$(function () {
    $("#addElement").click(function () {
        var processName = $("#ProcessName").val();

        // I've tried this method
        $.post('@Url.Action("AddProcessName")', processName, function (data, status) {
                    alert(data)
        });

       // And also this one, but both of them don't work.
       // I did not try them at the same time, of course
        $.ajax({
            type: "POST",
            url: '@Url.Action("AddProcessName")',
            data: processName,
            dataType: 'text',
            success: function (response) {
                alert(response)
                };
        });
    });
});

Server side:

[HttpPost]
public IActionResult AddProcessName(string data)
{
    pm.ID = 1;
    pm.Name = data; // I put a breakpoint here to check the value of 'data'
    return Content(pm.Name);
}

1 Answer 1

7

You're telling your Action to expect a variable named data, yet you're not sending that. You need to change the data property of your jQuery AJAX request to this:

data: { data: processName },

I'd also suggest you return JSON from the Action as plain text can be flaky at best due to the way whitespace may or may not be interpreted. Try this:

$("#addElement").click(function () {
  $.ajax({
    type: "POST",
    url: '@Url.Action("AddProcessName")',
    data: { 
      data: $("#ProcessName").val() 
    },
    dataType: 'json',
    success: function(response) {
      // use console.log for debugging, and access the property of the deserialised object
      console.log(response.Name); 
    };
  });
});
[HttpPost]
public IActionResult AddProcessName(string data)
{
    pm.ID = 1;
    pm.Name = data;
    return Json(new { Name = pm.Name });
    // or just:
    // return Json(pm);
}
Sign up to request clarification or add additional context in comments.

1 Comment

It works! Thank you very much. Thanks for the tip to use JSON instead.

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.