通过 POST (ajax) 发送 JSON 数据并从 Controller (MVC) 接收 json 响应 [英] Send JSON data via POST (ajax) and receive json response from Controller (MVC)
本文介绍了通过 POST (ajax) 发送 JSON 数据并从 Controller (MVC) 接收 json 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 javascript 中创建了一个这样的函数:
I created a function in javascript like that:
function addNewManufacturer() {
var name = $("#id-manuf-name").val();
var address = $("#id-manuf-address").val();
var phone = $("#id-manuf-phone").val();
var sendInfo = {
Name: name,
Address: address,
Phone: phone
};
$.ajax({
type: "POST",
url: "/Home/Add",
dataType: "json",
success: function (msg) {
if (msg) {
alert("Somebody" + name + " was added in list !");
location.reload(true);
} else {
alert("Cannot add to list !");
}
},
data: sendInfo
});
}
我调用了 jquery.json-2.3.min.js
脚本文件,并将其用于 toJSON(array)
方法.
I called jquery.json-2.3.min.js
script file and I used it for toJSON(array)
method.
在控制器中,我有这个 Add
动作
In controller, I have this Add
action
[HttpPost]
public ActionResult Add(PersonSheets sendInfo) {
bool success = _addSomethingInList.AddNewSomething( sendInfo );
return this.Json( new {
msg = success
});
}
但是 sendInfo
作为方法参数变为空.
But sendInfo
as method parameter becomes null.
模型:
public struct PersonSheets
{
public int Id;
public string Name;
public string Address;
public string Phone;
}
public class PersonModel
{
private List<PersonSheets> _list;
public PersonModel() {
_list= GetFakeData();
}
public bool AddNewSomething(PersonSheets info) {
if ( (info as object) == null ) {
throw new ArgumentException( "Person list cannot be empty", "info" );
}
PersonSheets item= new PersonSheets();
item.Id = GetMaximumIdValueFromList( _list) + 1;
item.Name = info.Name;
item.Address = info.Address;
item.Phone = info.Phone;
_list.Add(item);
return true;
}
}
当使用 POST 发送数据时,我如何在 action 方法中执行?
How could I do in action method when the data was sent with POST ?
不知道怎么用.此外,是否可以通过 JSON 发回响应(到 ajax)?
I don't know how to use. Also, it is possible to send back the response (to ajax) via JSON ?
推荐答案
创建模型
public class Person
{
public string Name { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
}
像下面这样的控制器
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>
这篇关于通过 POST (ajax) 发送 JSON 数据并从 Controller (MVC) 接收 json 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文