Reputation: 53
How can I post multiple strings form jquery ajax to a C# controller action? I have this working with one string but not sure how to post more than one string to a method in c# taking two string parameters.
Jquery code:
var data = {
date: "s",
index: "sa"
}
$.ajax({
url: "/Home/PersistTimeOfDay",
type: 'post',
data: JSON.stringify(data),
contentType: 'application/json',
success: function(response) {
alert(response);
},
error: function(jqXHR, textStatus, errorThrown){
alert(jqXHR.status);
}
})
C# code:
[Microsoft.AspNetCore.Mvc.HttpPost]
public IActionResult PersistTimeOfDay([FromBody] string date, [FromBody] string index)
{
return Json("s");
}
Would love to finally achieve this! I have tried a number of combinations and either get one or all values null.
Upvotes: 0
Views: 1928
Reputation: 14218
You can try this way to achieve it
C#
public class ParamModel
{
public string date { get; set; }
public string index { get; set; }
}
[HttpPost]
public IActionResult PersistTimeOfDay([FromBody] ParamModel model)
{
return Json("s");
}
Javascript
$.ajax({
type: "POST",
url: "/Home/PersistTimeOfDay",
contentType: "application/json",
dataType: "json",
data: JSON.stringify({ date: "s" , date:"sa" }),
success: function(response) {
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown){
alert(jqXHR.status);
}
});
Upvotes: 0
Reputation: 753
By doing like this,
you can pass multiple parameters as many you want
Just pass data as model from your js like
var employee = new Object();
employee.Name = "ABC"
employee.Address = "PUNE";
employee.Location = "PUNE";
$.ajax({
type: "POST",
url: "/Home/PersistTimeOfDay",
data: JSON.stringify(employee),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
// Do your code here
},
failure: function(response) {
alert(response.responseText);
},
error: function(response) {
alert(response.responseText);
}
});
and create one model as Employee like
public class Employee
{
public string Name {get;set;}
public string Designation {get;set;}
public string Location {get;set;}
}
and just add code in your controller
[HttpPost]
public JsonResult PersistTimeOfDay(Employee employeeData) {
Employee employee = new Employee {
Name = employeeData.Name,
Designation = employeeData.Designation,
Location = employeeData.Location
};
return Json(employee, JsonRequestBehavior.AllowGet);
}
Upvotes: 1
Reputation: 835
Try this.Is your url correct?
$.ajax({
url: "/Home/PersistTimeOfDay",
type: 'post',
data: JSON.stringify( { "date":"s" , "date":"sa" }),
contentType: 'application/json',
success: function(response) {
alert(response);
},
error: function(jqXHR, textStatus, errorThrown){
alert(jqXHR.status);
}
})
But i use this method to pass whole form data
data:$('form#yourformuniqueid').serialize(),
Upvotes: 0