![](/img/trans.png)
[英]How to use correctly JSON.stringify with an PHP returned JS object
[英]How to use returned JSON.stringify array in C#
我有 JavaScript function 我有一個數組,當我將該數組發送到我的 C# controller 時,它應該以我的 controller 應該理解的方式。
JavaScript function
function Check(obj) {
var eArray = $('..').map(function () {
return this.getAttribute("value");
}).get();
$.ajax({
url: "/Order/Check",
data: { GUID: JSON.stringify(eArray) },
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
});
我的 Controller
public ActionResult Check()
{
string guid = HttpContext.Request["GUID"];
var result = //send the result
return Json(result, JsonRequestBehavior.AllowGet);
}
我想在我的 controller 中得到一個數組。
我不太確定你想要達到什么目的。 從我在您的評論中看到的內容來看,您正在向您的 controller 發送一組 GUID,但這會導致它作為字符串發送,而您需要一個數組。
我測試了您的代碼並對其進行了一些修改:
$.ajax({
type: "POST",
url: /your url/,
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
data: JSON.stringify({GUID: eArray}),
});
其中 eArray let eArray = ['D5FAF478-CF43-40E1-BE79-BB90147A3194', '2E79B23E-D264-4901-A065-7E0B7032A5D8']
然后,在我的 controller 中,我收到的是 model:
public class Dto
{
public string[] GUID { get; set; }
}
然后,您可以像這樣使用它:
[HttpPost]
public IActionResult Post([FromBody] Dto dto)
{
var listOfGuids = dto.GUID.Select(guid => Guid.Parse(guid)).ToList();
var result = Services.CheckRecords(listOfGuids);
...
}
不幸的是,標准的JavaScriptSerializer.Deserialize
似乎不處理 Guid 類型。
因此,我會用 go 之類的東西
public ActionResult Check()
{
string guidsStr = HttpContext.Request["GUID"];
var guids = new List<Guid>();
foreach (var guid in Regex.Replace(guidsStr, "[\\[\\\"\\]]", "").Split(",")) {
Guid newGuid;
if (Guid.TryParse(guid, out newGuid)) {
guids.Add(newGuid);
} else {
// handle invalid guide value
}
}
// guids list now contains parsed Guid objects
// do here what you need to do with the list of guids
return Json(result, JsonRequestBehavior.AllowGet);
}
請讓我知道這可不可以幫你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.