通过POST(ajax)发送JSON数据并从Controller(MVC)接收json响应我在javascript中创建了一个函数: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)方法。在控制器中,我有这个Add动作[HttpPost]public ActionResult Add(PersonSheets sendInfo) {
bool success = _addSomethingInList.AddNewSomething( sendInfo );
return this.Json( new {
msg = success });}但是sendInfo当方法参数变为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方法呢?我不知道怎么用。此外,可以通过JSON发回响应(到ajax)?谢谢
3 回答
浮云间
TA贡献1829条经验 获得超4个赞
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) { ... } });
并在行动
public ActionResult AddDomain(IEnumerable<PersonSheets> SendInfo){...
你可以像这样绑定你的数组
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);});
希望这可以帮到你。
- 3 回答
- 0 关注
- 1481 浏览
相关问题推荐
添加回答
举报
0/150
提交
取消