Home > Software design >  Ajax Call to ASP.NET MVC controller
Ajax Call to ASP.NET MVC controller

Time:07-26

The jQuery code is :

var props = [
    { "Name": "firstName", "Value": "firstValue" }, 
    { "Name": "secondName", "Value": "secondValue" }
];

$.ajax({
     url: '/myURL',
     contentType: "application/json",
     async: true,
     type: "POST",
     data: JSON.stringify(props),
     error: function (jqXHR, textStatus, errorThrown) {
         console.log("FAIL: "   errorThrown);
     },
     success: function (data, textStatus, jqXHR) {
         console.log("SUCCESS!");
     }
});

The ASP.NET MVC controller

[HttpPost]
public async Task<ActionResult> Test(string myValue)
{
    return Json("something");
}

I hit the controller but myValue is null all the time.

Any idea ?

Thanks,

CodePudding user response:

Modify your API action to expect to receive the input of List<Prop> type.

[HttpPost]
public async Task<ActionResult> Test(List<Prop> myValue)
{
    return Json("something");
}
public class Prop
{
    public string Name { get; set; }
    public string Value { get; set; }
}

Demo

enter image description here

CodePudding user response:

In the view side script the myValue parameter name should be used to make binding to work properly:

var props = [

      { "Name": "firstName", "Value": "firstValue" },
      { "Name": "secondName", "Value": "secondValue" }
  ];

  $.ajax({
      url: '@Url.Action("Test", "Home")',
      contentType: "application/json",
      async: true,
      type: "POST",
      data: { myValue: JSON.stringify(props) },
      dataType: "json",

      error: function (jqXHR, textStatus, errorThrown) {
          console.log("FAIL: "   errorThrown);
      },
      success: function (data, textStatus, jqXHR) {
          console.log("SUCCESS!");
      }
  });

On the controller side:

[HttpPost]               
public async Task<ActionResult> Test(string myValue)
{            
    var data = JsonConvert.DeserializeObject(myValue);
    // TODO: ...
    
    return Json("Success");
}

enter image description here

In the code above the @Url.Action("Test", "Home")' is used and it should be replaced by proper url.

  • Related