2016-04-28 139 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> 

發表你的看法......這對我的作品......