通常,我將資料發送到帶有 URL 的控制器,使用類名后跟方法名/Parent?handler=InitData,或者/Parent/InitData如果@page "{handler?}"是在頁面中定義的。
但是,與繼承主父控制器的子控制器相比,如何做到這一點呢?
我正在尋找的是使用類似于此的語法呼叫子控制器內的方法/Parent/Child/Test。請注意,該呼叫是在嵌入主父頁面的部分頁面中進行的。
關于如何實作這一目標的任何想法?(我知道這與路由有關,但我只是不明白該怎么做)
這是我到目前為止所擁有的
部分頁面
@using App.Models.PagesViews.PartialPage
@model PartialPage // <-- partial parent model has access to PartialPage_Add and PartialPage_Delete children
<script type="module">
$.ajax({
url: "/Parent/Child/Test", <-- should call child controller method but is not working!!!
type: "post",
contentType: "application/json; charset=utf-8",
dataType: "json",
...
});
</script>
<div>
<!--... html code...-->
<div>
父頁面
@page "{handler?}"
@model App.Pages.ParentModel
@section head {
...
}
<div>
<partial name="_PartialPage" model="Model.partialPage_Add"
...
<partial name="_PartialPage" model="Model.partialPage_Delete"
</div>
父頁面控制器
public class ParentModel : PageModel
{
private readonly DatabaseContext _dbContext;
public readonly PartialPage_Add partialPage_Add; // <-- PartialPage_Add is a child of PartialPage
public readonly PartialPage_Delete partialPage_Delete; // <-- PartialPage_Delete is a child of PartialPage
public MainModel(DatabaseContext _dbContext)
{
this._dbContext = _dbContext;
}
public IActionResult OnGet() => Page();
}
子頁面控制器
public class ChildModel : ParentModel
{
public ChildModel(DatabaseContext _dbContext) : base(_dbContext)
{
}
public void OnPostTest() // <-- Access this method from partial page
{
Log.Debug($"Successfully called method Test() in class ChildModel");
....
}
}
uj5u.com熱心網友回復:
我想你可能誤解了 Razor Pages 和 MVC Controller 的用法。
Razor Pages 應包含.cshtml宣告的檔案@Page和與.cshtml.cs檔案同名的.cshtml檔案。此外,該.cshtml.cs檔案應繼承PageModel或PageModel的繼承類。
你的ChildModelextendsParentModel是的繼承類PageModel,如果你的專案中沒有相應.cshtml的,那ChildModel只是一個簡單的類,ajax是無法呼叫的。
所以你需要確保你的專案包含一個Child.cshtml并@page "{handler?}"在其中宣告。然后正確的 url 應該是/Child/Test.
如果要使用父級作為后綴,請將頁面路由模板更改為@Page "/Parent/Child/{handler?}".
此外,如果您在 Razor Pages 中使用 ajax,則必須將AntiForgeryToken連同您想要的資料一起發送到Post方法。
參考:
如何將 jQuery 腳本的結果值轉換為 ASP.NET Core MVC 中同一剃刀頁面中的 C# 代碼?
對于MVC controller,不管你的專案有沒有這個.cshtml檔案,你也可以點擊action,因為你可以在Startup.cs/Program.cs中配置路由模板或者直接使用[Route]屬性。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/537510.html
上一篇:類不繼承時super()的用途
下一篇:__init__如何用于繼承
