Send JSON data via POST (ajax) and receive json response from Controller (MVC)
Solution 1:
var SendInfo= { SendInfo: [... your elements ...]};
$.ajax({
type: 'post',
url: 'Your-URI',
data: JSON.stringify(SendInfo),
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (data) {
...
}
});
and in action
public ActionResult AddDomain(IEnumerable<PersonSheets> SendInfo){
...
you can bind your array like this
var SendInfo = [];
$(this).parents('table').find('input:checked').each(function () {
var domain = {
name: $("#id-manuf-name").val(),
address: $("#id-manuf-address").val(),
phone: $("#id-manuf-phone").val(),
}
SendInfo.push(domain);
});
hope this can help you.
Solution 2:
Create a model
public class Person
{
public string Name { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
}
Controllers Like Below
public ActionResult PersonTest()
{
return View();
}
[HttpPost]
public ActionResult PersonSubmit(Vh.Web.Models.Person person)
{
System.Threading.Thread.Sleep(2000); /*simulating slow connection*/
/*Do something with object person*/
return Json(new {msg="Successfully added "+person.Name });
}
Javascript
<script type="text/javascript">
function send() {
var person = {
name: $("#id-name").val(),
address:$("#id-address").val(),
phone:$("#id-phone").val()
}
$('#target').html('sending..');
$.ajax({
url: '/test/PersonSubmit',
type: 'post',
dataType: 'json',
contentType: 'application/json',
success: function (data) {
$('#target').html(data.msg);
},
data: JSON.stringify(person)
});
}
</script>
Solution 3:
Use JSON.stringify(<data>)
.
Change your code: data: sendInfo
to data: JSON.stringify(sendInfo)
.
Hope this can help you.
Solution 4:
To post JSON, you will need to stringify it. JSON.stringify
and set the processData
option to false.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=UTF-8",
complete: callback
});