gpt4 book ai didi

c# - 我如何通过 AJAX 将这种复杂类型发布到我的 MVC 操作中?

转载 作者:行者123 更新时间:2023-11-30 16:51:35 24 4
gpt4 key购买 nike

我正在尝试将复杂数据类型发布到 MVC Controller 操作,但数据为空或包含默认值。

这里是客户端(它将 type 参数设置为 data.complexType [例如,type: data.complexType] 和发布它):

enter image description here

这是关于 POST 操作的问题:

enter image description here

它可以很好地从 GET 获取复杂类型,但我现在如何才能将相同的复杂类型 POST 回 Controller ,使其不再包含空值或默认值?

这是我的HomeController.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplication0.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}

[HttpPost]
public ActionResult PostComplexType(ComplexType type)
{
return Json(new { complexType = type });
}

public ActionResult GetComplexType()
{
var result = new ComplexType
{
TypeOne = 1,
TypeTwo = "2",
TypeThree = new ComplexNestedType
{
TypeOne = 1,
TypeTwo = "2"
}
};
return Json(new { complexType = result }, JsonRequestBehavior.AllowGet);
}
}

public class ComplexType
{
public Int32 TypeOne { get; set; }
public String TypeTwo { get; set; }
public ComplexNestedType TypeThree { get; set; }
}

public class ComplexNestedType
{
public Int32 TypeOne { get; set; }
public String TypeTwo { get; set; }
}
}

这是我的Index.cshtml:

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@section scripts {
<script>
$("#exampleButton").click(function () {
$.ajax({
url: "@Url.Action("GetComplexType", "Home")",
type: "get",
error: function () {
alert("There was an error calling GetComplexType().")
},
success: function (data) {
debugger;
$.ajax({
url: "@Url.Action("PostComplexType", "Home")",
type: "post",
data: {
type: data.complexType
},
error: function () {
alert("There was an error calling PostComplexType().")
},
success: function (data) {
debugger;
}
});
}
});
});
</script>
}
<button id="exampleButton" type="button">Example</button>

编辑:我尝试直接设置data: data.complexType,但它不会解析嵌套类型:

enter image description here

最佳答案

你可以使用 JSON.stringify

$.ajax({
url: "@Url.Action("PostComplexType", "Home")",
type: "post",
data: JSON.stringify(data.complexType),
contentType: "application/json; charset=UTF-8",
error: function () {
alert("There was an error calling PostComplexType().")
},
success: function (data) {
debugger;
}
});

关于c# - 我如何通过 AJAX 将这种复杂类型发布到我的 MVC 操作中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33716097/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com