1

It works but the passed parameter is always null, this code is working on my other project on the ASP.NET Framework(.Net Framework) but not working in ASP.NET Core.

var inputParams = "{namex: '" + 'testdata' + "'}";

var xhr = $.ajax({
    url: "/Test/MyFunction",
    type: 'POST',
    dataType: 'json',
    data: inputParams,
    contentType: 'application/json; charset=utf-8',
    success: function (msg) {

    },
    error: function (xhr) {

    }
});

The Test Controller contains:

   [HttpPost]
   public JsonResult MyFunction(string namex) <--- namex is always NULL
    {
        return Json(false);
    }
0

3 Answers 3

1

The data is not being sent in the correct format for the content to properly bind to teh action

First construct the payload properly to be posted

var inputParams = { namex: "testdata" }; //<-- NOTE JavaScript

var xhr = $.ajax({
    url: "/Test/MyFunction",
    type: 'POST',
    dataType: 'json',
    data: JSON.stringify(inputParams), //<-- NOTE CONVERSION TO JSON
    contentType: 'application/json; charset=utf-8',
    success: function (msg) {

    },
    error: function (xhr) {

    }
});

Next create a model to hold the data on the server side

public class MyModel {
    public string namex { get; set;}
}

Finally refactor the action to bind to the expected data from the body of the request

[HttpPost]
public IActionResult MyFunction([FromBody]MyModel model) {
    if(ModelState.IsValid) {
        string namex = model.namex;
        return Ok();
    }
    return BadRequest(ModelState);
}

Reference Model Binding in ASP.NET Core

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

2 Comments

I found another answer like yours but why should I create a model(MyModel) just to pass a simple variable to my controller, there is no way to do it without creating an extra model?
@motevalizadeh is that how the actual code is going to be used? I am just suggesting the approach most recommended by documentation for model binding in Asp.Net Core. Review the link provided in the answer.
0

Add FromBodyAttribute to parameter

MyFunction([FromBody] string namex)

Comments

0

just sent it without object

var inputParams = 'testdata';

var xhr = $.ajax({
    url: "/Test/MyFunction",
    type: 'POST',
    dataType: 'json',
    data: inputParams,
    contentType: 'application/json; charset=utf-8',
    success: function (msg) {

    },
    error: function (xhr) {

    }
});

or



var xhr = $.ajax({
    url: "/Test/MyFunction?namex=testdata", // <------ here
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    success: function (msg) {

    },
    error: function (xhr) {

    }
});

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.