2016-04-28 138 views
-2

我仍然试图了解如何将JSON对象列表发送到控制器以将数据保存到SQL Server数据库表“受邀者”中。控制器的JSON对象列表

一个例子会非常有用。

JSON:

[{Email :"[email protected]",Presence :"nodig"},{Email :"[email protected]",Presence :"gewenst"}] 

型号:

public class Invitee 
{ 
    public int Id { get; set; } 
    public int AppId { get; set; } 
    public string Email { get; set; } 
    public string Presence { get; set; } 
}; 

控制器:(模型返回一个空exeption,的ModelState =真)

[HttpPost] 
public JsonResult InviteeSave(List<Invitee> model) 
{ 
    if (ModelState.IsValid) 
    { 
     using (var db = new MainDbContext()) 
     { 
      var dbInv = db.Invitees.Create(); 

      foreach (var inv in model) 
      { 
       dbInv.AppId = 35; 
       dbInv.Email = inv.Email; 
       dbInv.Presence = inv.Presence; 

       db.Invitees.Add(dbInv); 
      } 

      db.SaveChanges(); 
     } 
    } 
    else 
    { 
     ModelState.AddModelError("", "Something went wrong"); 
    } 
    return Json(model); 
} 

jQuery的AJAX:

$.ajax({ 
    url: '@Url.Action("InviteeSave", "App")', 
    dataType: "json", 
    type: "POST", 
    accept: 'appication/json; charset=utf-8', 
    cache: false, 
    data: JSON.stringify(jsonData), 
    success: function (data) { 
     if (data.success) { 
      alert("Met succes !"); 
     } 
    }, 
    error: function (xhr) { 
     alert('error'); 
    } 
}); 
+0

有什么不对您的AJAX请求;该问题在C#中。什么是'null'?如果需要,在Action中放置一个断点并逐步完成。 –

+0

'appication'中的拼写错误(缺少'l') –

+0

对不起。 在控制器'模型'中返回一个NULL异常 – wintee

回答

0

对不起,您无法发送用户定义类型的集合(列表)。 有一个工作。

使控制器参数类型为

的DataTable类型的C#

然后通过ajax发表您的数据。这个对我有用。

$.ajax({ 
     type: "POST", 
     url: "URL/api/.....", 
     data: {Email :"[email protected]",Presence :"nodig"},{Email :"[email protected]",Presence :"gewenst"}, 
    }).done(function(data){ 
     console.log(data) 
}); 

我有这个工作在我的web应用程序目前

编辑: 您可以发布清单;字符串列表到控制器参数。那么你可以相应地对你的数据进行排序。

0

不,您可以将物品收集发送给控制器后操作方法。

[HttpPost] 
public JsonResult InviteeSave(List<Invitee> model) 
{ 
    //Your code goes here 
} 

JS: //(网址:应该是actionname,控制器在您使用@ Url.Action(情况),或者干脆放弃网址: '/控制器/方法/')

$.ajax({ 
      url: "InviteeSave", 
      dataType: "json", 
      type: "POST", 
      contentType: 'application/json; charset=utf-8', 
      cache: false, 
      data: JSON.stringify({ model: jsonData }), 
      success: function(data) { 
       if (data.success) { 
        alert("Met succes !"); 
       } 
      }, 
      error: function(xhr) { 
       alert('error' + 'Came here'); 
      } 
     }); 

我的看法是

<form id="frmInvitee" action="javascript:void(0)"> 
    <input type="submit" name="BtnSumbit" id="BtnSumbit" /> 
</form> 

发表你的看法......这对我的作品......