簡體   English   中英

MVC:將對象和整數作為JSON發送到控制器

[英]MVC: Send object and integer to controller as JSON

我正在嘗試使用jQuery AJAX向我的控制器操作發送自定義對象和一個整數。

[HttpPost]
public JsonResult GetFilenameSuggestion(Document document, int tradeId)
{
    //do stuff...
}

在我的JS中,我嘗試以多種方式創建發送到控制器的json,包括:

var json = JSON.stringify({ document: document, tradeId: tradeId });
//or
var json = { document: JSON.stringify(document), tradeId: tradeId };
//or
var json = { document: document, tradeId: tradeId };

這是我的jQuery AJAX:

$.ajax({
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        url: "/Document/GetFilenameSuggestion",
        data: json,
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        //do bad stuff...
    },
    success: function (data) {
        //do good stuff...
});

有關如何執行此操作的任何建議? 我在ajax發布時收到內部服務器錯誤,我有99%的把握是由於參數如何傳遞到控制器操作。

使用JSON.stringify將您的JavaScript對象轉換為json字符串版本,並將contentType指定為“ application/json ”。

下面的代碼應該可以正常工作。

var model = { document: { DocumentName: "Dummy" }, tradeId: 34 };

$.ajax({
    type: "POST",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    url: "/Document/GetFilenameSuggestion",
    data: JSON.stringify(model),
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        //do bad stuff...
    },
    success: function(data) {
        //do good stuff...
    }
});

為此操作方法簽名

[HttpPost]
public JsonResult GetFilenameSuggestion(Document document, int tradeId)
{
    // to do : return some useful JSON data
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM