Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP POST request to C# Controller

I'm trying to make HTTP POST request to my C# controller, but I need to send in data an array, so I tried with JSON.stringify but when I start debugging, the input parameter in my controller is NULL? I'm receiving a list from external API for weather forecast, so I need to create for each item in list new variable, that has some fields like : max and min temperature, description, humidity, pressure etc, and then of course fill these fields with data and add that variable to my array. Then I need to pass this array to my controller so I could store it in my database... What type should I put in my controller so it would not be NULL? I'm totally new here so please help, any help is really more then welcome!

Below is code I have just to try :

 var myData = { id:100, description:"some text"};
 var myDataArray= new Array();   
 myDataArray.push(myData);   
 $.ajax({
    dataType: "json",
    type: "POST",
    url: "/Weather1/Weather_post",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify(myDataArray),
    success: function (data) {
        console.log(("OK"));
    },
    error: function (error)
    { console.log("NOT OK"); }
})

Controller:

[HttpPost]
public JsonResult Weather_post(String MyModuleList)
like image 622
Edna Avatar asked Jul 12 '26 15:07

Edna


1 Answers

Model binding has no idea what "MyModuleList" is. You can use a strongly typed model here and MVC will bind the JSON to it.

Consider JSON:

var data = {
    moduleList: [
        { id:100, description:"some text"}
    ];
};

and models:

public class ModuleListModel
{
    public List<ModuleModel> ModuleList { get; set; }
}
public class ModuleModel
{
    public int Id { get; set; }
    public string Description { get; set; }
}

and action:

[HttpPost]
public JsonResult Weather_post(ModuleListModel model)
{ 
    ... 
}

Combine that with @Timothy Shields' answer:

You're missing processData: false in your ajax call. Without that, ajax is going to try to pack the data into the URL query string. (See here: http://api.jquery.com/jQuery.ajax/)

and you should be good.

like image 198
Paul Fleming Avatar answered Jul 15 '26 03:07

Paul Fleming