3

I am developing .net core application.i need to pass java script values to my controller using Post method. i am using java script code is below

 data = {'imageValue':'some test'}
    $.ajax({ 
      type: 'Post',          
      url: '/Home/UploadData',      
      dataType: 'json',
      contentType: 'application/json',
      data: data,
      success: function (data) {
      alert(data);      
      console.log('sample');                      
      },     
      error:  function(){
    }
    });

my controller is [HttpPost]public string UploadData([FromBody] string imageValue) {return imageValue;} but imageValue always it return null.if any mistake in my code please solve the problem.

3
  • what returns null? what is your expected behavior and what is happening now and when ? Commented Jun 21, 2017 at 14:13
  • Can you post the C# controller? I'd imagine you're missing the [FromBody] attribute Commented Jun 21, 2017 at 14:13
  • Do you sending correct json object from server side? Commented Jun 21, 2017 at 14:16

1 Answer 1

4

When you make the ajax call, you should stringify the javascript object and send it. You can use the JSON.stringify method to convert the js object to it's JSON string equivalent.

var data = {'imageValue':'some test'}
$.ajax({
    type: 'Post',
    url: '/Home/UploadData',
    dataType: 'json',
    contentType: 'application/json',
    data: JSON.stringify(data),
    success: function (data) {

        console.log('sample', data);
    },
    error:  function(){
    }
});

Now since the ajax call is sending the data in the request body (since it is a POST request),You need to decorate the HttpPost action method parameter with [FromBody] attribute so that model binder knows it should read the data from the request body and map to the method parameter(YourViewModel) object.

public IActionResult UploadData([FromBody] YourViewModel d)
{
    return Json(d);
}
Sign up to request clarification or add additional context in comments.

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.