2014-02-05 137 views
53

我一直在嘗試整個下午通過Web爬行嘗試接收操作控制器中的JSON對象。如何接收JSON作爲MVC 5操作方法參數

什麼是正確或更簡單的方法去做呢?

我曾嘗試以下: 1:

//Post/ Roles/AddUser 
    [HttpPost] 
    public ActionResult AddUser(String model) 
    { 
     if(model != null) 
     { 
      return Json("Success"); 
     }else 
     { 
      return Json("An Error Has occoured"); 
     } 

    } 

這給了我在我輸入一個空值。

2:

//Post/ Roles/AddUser 
    [HttpPost] 
    public ActionResult AddUser(IDictionary<string, object> model) 
    { 
     if(model != null) 
     { 
      return Json("Success"); 
     }else 
     { 
      return Json("An Error Has occoured"); 
     } 

    } 

,給了我一個500錯誤jQuery開發方面正試圖張貼到了嗎? (意思是它沒有正確綁定)。

這裏是我的jQuery代碼:

<script> 
function submitForm() { 

    var usersRoles = new Array; 
    jQuery("#dualSelectRoles2 option").each(function() { 
     usersRoles.push(jQuery(this).val()); 
    }); 
    console.log(usersRoles); 

    jQuery.ajax({ 
     type: "POST", 
     url: "@Url.Action("AddUser")", 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     data: JSON.stringify(usersRoles), 
     success: function (data) { alert(data); }, 
     failure: function (errMsg) { 
      alert(errMsg); 
     } 
    }); 
} 

所有我想要做的就是接受我的JSON對象在我的MVC的行動?

+0

雖然這指定MVC5,解決方案是相同的,所以這是[將JSON數據發佈到ASP.NET MVC]的副本(http://stackoverflow.com/questions/ 4164114/posting-json-data-to-asp-net-mvc) –

回答

57

不幸的是字典有問題總是與模型MVC綁定。 Read the full story here。因此,我們必須創建我們自己的自定義模型聯編程序,以將字典作爲控制器操作的參數。

爲了解決您的要求,這裏是工作的解決方案 -

首先創建下面的方式您的ViewModels。 PersonModel可以有RoleModel的列表。

public class PersonModel 
{ 
    public List<RoleModel> Roles { get; set; } 
    public string Name { get; set; } 
} 

public class RoleModel 
{ 
    public string RoleName { get; set;} 
    public string Description { get; set;} 
} 

然後讓這將是服務的基本指數視圖索引操作 -

public ActionResult Index() 
    { 
     return View(); 
    } 

索引視圖將具有以下JQuery的AJAX POST操作 -

<script src="~/Scripts/jquery-1.10.2.min.js"></script> 
<script> 
    $(function() { 
     $('#click1').click(function (e) { 

      var jsonObject = { 
       "Name" : "Rami", 
       "Roles": [{ "RoleName": "Admin", "Description" : "Admin Role"}, { "RoleName": "User", "Description" : "User Role"}] 
      }; 

      $.ajax({ 
       url: "@Url.Action("AddUser")", 
       type: "POST", 
       data: JSON.stringify(jsonObject), 
       contentType: "application/json; charset=utf-8", 
       dataType: "json", 
       error: function (response) { 
        alert(response.responseText); 
      }, 
       success: function (response) { 
        alert(response); 
       } 
      }); 

     }); 
    }); 
</script> 

<input type="button" value="click1" id="click1" /> 

Index操作職位,以ADDUSER動作 -

[HttpPost] 
    public ActionResult AddUser(PersonModel model) 
    { 
     if (model != null) 
     { 
      return Json("Success"); 
     } 
     else 
     { 
      return Json("An Error Has occoured"); 
     } 

    } 

所以現在,當帖子發生時,您可以獲取動作模型參數中的所有發佈數據。

enter image description here

+1

嗯,所以它需要是一個POST?我有同樣的問題,模型的參數是'null',但是當我將POST添加到我的ajax調用和mvc控制器時,我的模型不再爲空。唯一困擾我的是,如果您將字符串賦給javascript中的某個屬性,並將此對象與ajax一起傳遞給服務器,那麼在C#中,服務器會將這些空字符串屬性讀作'null'。我寧願他們在C#中也是一個空字符串。 – QuantumHive

+0

發現上述問題的解決方案:http://stackoverflow.com/questions/12734083/string-empty-converted-to-null-when-passing-json-object-to-mvc-controller – QuantumHive

+2

我複製/粘貼這和我'命中'的方法,但model.Name爲null(如同角色) 我正在使用.NET核心 - 是否有一個設置,我必須改變? –

11

這裏有幾個問題。首先,您需要確保將您的JSON對象綁定回控制器中的模型。這是通過改變

data: JSON.stringify(usersRoles), 

data: { model: JSON.stringify(usersRoles) }, 

其次,你沒有正確使用您的jQuery電話綁定類型。如果刪除

contentType: "application/json; charset=utf-8", 

它將固有地綁定回字符串。

總之,使用第一的ActionResult方法及以下的jQuery AJAX調用:

jQuery.ajax({ 
     type: "POST", 
     url: "@Url.Action("AddUser")", 
     dataType: "json", 
     data: { model: JSON.stringify(usersRoles) }, 
     success: function (data) { alert(data); }, 
     failure: function (errMsg) { 
     alert(errMsg); 
     } 
    }); 
+0

這對我有用,我擺脫了stringify,因爲它把引號放在我的字符串中,但是當我沒有調用stringify時,它沒有引號控制器。這允許我通過一個帖子將一個字符串放入我的控制器中。這讓我滿意。 –

4

您要發送的字符串的數組

var usersRoles = []; 
jQuery("#dualSelectRoles2 option").each(function() { 
    usersRoles.push(jQuery(this).val()); 
}); 

因此更改模型類型相應

public ActionResult AddUser(List<string> model) 
{ 
} 
+0

+1這應該做的工作 – Leo

+0

所以你說我不應該jsonify的數據? – Zapnologica

+0

@Zapnologica,'data:JSON.stringify(usersRoles)'只是正確的,你需要。你的ajax代碼是完美的。但你的操作方法需要一個字典參數,但你要發送一個字符串數組:) –

1

FWIW,這並沒有爲我工作,直到我有這樣的阿賈克斯電話:

contentType: "application/json; charset=utf-8", 

使用Asp.Net MVC 4.