Razor 是一種允許您向網頁中嵌入基於服務器的代碼(Visual Basic 和 C#)的標記語法。
當網頁被寫入瀏覽器時,基於服務器的代碼能夠創建動態內容。
在網頁加載時,服務器在向瀏覽器返回頁面之前,會執行頁面內的基於服務器代碼。
由於是在服務器上運行,這種代碼能執行復雜的任務,比如訪問數據庫。
razor pages 的渲染是由服務器完成的,后端Razor直接渲染模版,這就會導致服務器端的壓力,
所以在遇到數據量過大的地方,還是由前端來渲染比較好,這就牽涉到了如何利用ajax調用 razor pages的后端代碼了,
基於我的搜索結果,方式有兩種:
方式一
參考:https://www.jb51.net/article/133437.htm
參考:http://www.cnblogs.com/mebius4789/p/8685755.html
這個方式我個人認為比麻煩,大家可以自行查看鏈接
方式二
參考:https://www.learnrazorpages.com/security/request-verification#ajax-post-requests
這個方式也是我接受的方式:
操作步驟如下:
1、Startup文件的ConfigureServices方法,添加下段:
services.AddMvc().AddRazorPagesOptions(o => { o.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute()); });
整體如下:
services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1) .AddRazorPagesOptions(o => { o.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute()); });
2、Ajax請求
var postSubmit = $.ajax({ type: "POST", url: "/yourformhandler", data: JSON.stringify({ ... }), contentType: "application/json" }).done(function(response){ //... });
舉個栗子:
后端代碼:
public class Index1Model : PageModel { public void OnGet() { } //url:"Index" public IActionResult OnPost([FromBody]MyClass my) { return new JsonResult("Hello Response Back"); } //url: "Index?handler=Send" public ActionResult OnPostSend([FromBody] MyClass my) { return new JsonResult(my); } public class MyClass { public int speakerId { get; set; } public bool currentYear { get; set; } } }
前端Ajax調用:
<h1>Index1</h1> <button id="clickme">click me</button> @section Scripts { <script> $('#clickme').click(function (e) { var _data = { "speakerId": 12, "currentYear": true }; var postSubmit = $.ajax({ type: "POST", url: "Index1?handler=Send", data: JSON.stringify(_data), contentType: "application/json" }).done(function (response) { alert(response); }); }) </script> }