簡體   English   中英

在 Visual Studio 2022 中的另一個局部視圖(cshtml / cshtml.cs 文件)中訪問 Web API 響應 object

[英]Accessing of Web API response object in another partial view (cshtml / cshtml.cs file) in Visual Studio 2022

單擊按鈕將從 js 下面的部分視圖 1 中調用 function 並從 controller 獲取數據,並將被重定向到另一個部分視圖。 由於 controller 在另一個項目中並單獨托管,因此 controller 沒有返回部分視圖,因此如果 ajax 調用成功,我將重定向它。

$.ajax({
    type: "POST",
    url: url,
    data: JSON.stringify(paramObj),
    contentType: "application/json; charset=utf-8",
    traditional: true,
    success: function (response) {
        var userObject = response.internalObject;
    window.location.href = url2;
    },
    error: function (response, status, error) {
        if (response.responseText != undefined) {
            const obj = JSON.parse(response.responseText);
            fnShowMessage(obj.DisplayMessage);
        }
    }

});

我有來自 ajax 調用的“userObject”中的數據,需要在部分視圖中顯示,但我無法訪問它或不確定如何訪問它。

“partialview2.cshtml.cs”中 OnGet() 方法中的賦值能夠保留在“partialview2.cshtml”文件中。 但是如何在部分視圖 2 的代碼后面的部分視圖 1 中獲取我從 ajax 調用中獲得的值。

public class UserModel : PageModel
{
    [BindProperty]
    public UserObject UserObject { get; set; } = new();
    public void OnGet()
    {
        UserObject.UserName = "man";
    }
}

您可以嘗試在 OnGet 中返回JsonResult

ajax:

$.ajax({
                type: "POST",
                url: "/Home/Test",
                data: JSON.stringify(paramObj),
                contentType: "application/json; charset=utf-8",
                traditional: true,
                dataType: "json",
                success: function (response) {
                    var userObject = response;
                    window.location.href = url2;
                },
                error: function (response, status, error) {
                    if (response.responseText != undefined) {
                        const obj = JSON.parse(response.responseText);
                        fnShowMessage(obj.DisplayMessage);
                    }
                }
            });

OnGet 處理程序:

public class UserModel : PageModel
{
    [BindProperty]
    public UserObject UserObject { get; set; } = new();
    public JsonResult OnGet()
    {
        UserObject.UserName = "man";
        return new JsonResult(UserObject);
    }
}

暫無
暫無

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

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