簡體   English   中英

使用form.submit()使用對象參數將復雜的Json發送到控制器

[英]Sending complex Json to a controller with an object parameter using a form.submit()

我正在嘗試使用以下形式發送復雜的Json:

{  
   "Success":false,
   "ErrorMessage":{  
      "ErrorMessage":"Some Message",
      "ErrorType":"Serialization Failed",
      "SiteReportDescription":"Some Desc",
      "Status":false
   },
   "Result":null
}

到以下控制器:

[Authorize, HttpPost]
public ActionResult DoThing(ThingModel model)
{
    return Json(true);
}

它接受以下模型(ThingError是另一個對象,具有json中提到的四個字段):

public class ThingModel
{
    public bool Success { get; set; }

    public ThingError ErrorMessage { get; set; }

    public ThingResult Result { get; set; }
}

我使用以下兩種方法與此控制器進行通信:

    var form = $('<form method="post" enctype="multipart/form-data" style="visibility:hidden;"><input type="submit" name="model" /></form>');
        $(document.body).append(form);
        form.attr("action", '@Url.Action("DoThing", "Script")');
        form.find("input[name='model']").val(JsonString);
        form.submit();

        $.ajax({
            type: 'POST',
            url: '@Url.Action("DoThing", "Script")',
            contentType: "application/json; charset=utf-8",
            processData: false,
            dataType: 'json',
            data: JsonString,
            success: function (result) { }
            },
        });

這兩種通信方法都將與控制器交互,但是只有Ajax請求將發送一個json字符串,該字符串將轉換為控制器對象ThingModel,form.submit會將其保留為空。 這背后的原因是什么? 我在表格中做錯什么了嗎?

您需要在提琴手中捕獲它,以了解原因。

本質上,ajax調用傳遞了以下內容:

{“某事”:“ 123”}

而表單通過此:

{“ Model”:{“ Something”:“ 123”}}

不一樣。

暫無
暫無

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

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