猿问

.load 带有数据参数的 jQuery 方法,用于 Partial Razor 页面

我正在使用 Razor 页面,但无法使用 jquery .load 函数将 javascript 中的 dto 对象映射到模型中的类。


因此,用户单击 UI 中的按钮并运行以下 javascript:


$('#btnGoToResults').click(function (e) {

    var dto = {

        ID: 1,

        CODE: 5

    };

    $('#divPerformanceResults').load('/PerformanceSearch?handler=ResultsPartial', dto); // Gives error 400

}

我也尝试了以下方法而没有让它工作:


$('#divPerformanceResults').load('/PerformanceSearch?handler=ResultsPartial', JSON.stringify(dto)); // "works" since the code behind is hit but the dto values are 0 

还尝试用ajax重写:


// Gives error 400

$.ajax({

    url: '/PerformanceSearch?handler=ResultsPartial',

    data: JSON.stringify(dto),

    dataType: 'json',

    contentType: 'application/json',

    type: 'POST',

    success: function (data) {

        $('#divPerformanceResults').html(data);

    }

});

这是我试图将其映射到的模型:


public class RequestResultModel

{

    public int ID { get; set; }

    public int CODE { get; set; }

}

它是创建和返回分部视图的方法的参数,分部视图将包含所有过滤逻辑:


public PartialViewResult OnGetResultsPartial(RequestResultModel dto)

{

    Results = new List<PerformanceResultModel>()

    {

        ...

    };

    return new PartialViewResult

    {

        ViewName = "_PerformanceResults",

        ViewData = new ViewDataDictionary<List<PerformanceResultModel>>(ViewData, Results)

    };

}

该方法有效并且部分被渲染,所以所有这些都很好。这只是我需要开始工作的 dto,所以我可以过滤结果列表。我确实通过将方法参数切换为 int 来使以下内容起作用,但它只是一个参数,稍后我将需要多个输入。


$('#divPerformanceResults').load('/PerformanceSearch?handler=ResultsPartial', 'ID=15'); // This works. Only one param though

如果有任何提示,还附上 chrome 日志:

慕仙森
浏览 200回答 2
2回答

万千封印

行。经过更多的测试和研究,我最终访问了:https : //www.learnrazorpages.com/security/request-verification我发现在剃刀页面上添加了令牌,防止没有它的帖子。因此,您可以忽略全局级别或类级别的令牌验证,例如:[IgnoreAntiforgeryToken(Order = 1001)]public class IndexModel : PageModel{&nbsp; &nbsp; public void OnPost()&nbsp; &nbsp; {&nbsp; &nbsp; }}或者你可以像我在下面做的那样:首先,将方法重命名为 OnPost 而不是 OnGet:public PartialViewResult OnPostResultsPartial(RequestResultModel dto)然后在 javascript 调用中包含如下所示的令牌:$('#btnGoToResults').click(function (e) {&nbsp; &nbsp; var dto = {&nbsp; &nbsp; &nbsp; &nbsp; ID: 1,&nbsp; &nbsp; &nbsp; &nbsp; CODE: 5&nbsp; &nbsp; };&nbsp; &nbsp; $('#divPerformanceResults').load('/PerformanceSearch?handler=ResultsPartial',&nbsp;&nbsp; &nbsp; &nbsp; { dto: dto, __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val() });}就是这样!它现在将 javascript 对象与页面模型中的类正确映射 :) 希望这会帮助其他人!

ibeautiful

您的第一个版本 .load() 很好,如果 jquery load() 方法检测到 dto 参数为对象,它将执行 http post:$('#divPerformanceResults').load('/PerformanceSearch?handler=ResultsPartial', dto);然后您可以将 [HttpPost] 属性添加到您的 Action 以接受 post 方法&nbsp; &nbsp; [HttpPost]&nbsp; &nbsp; public PartialViewResult OnGetResultsPartial(WebApplication1.Models.RequestResultModel dto)&nbsp; &nbsp; {
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答