后处理程序上的部分页面模型未执行|ASP.NET Core Razor Pages 2.0



我有一个带有页面模型的局部视图。在页面模型类中,我有一个OnPost处理程序,它在提交表单时不会被调用。

_Subscribe.cshtml

@page
@model Shared._SubscribeModel
<div id="subscribe-for-updates">
<h4>Subscribe to keep up-to-date with any changes.</h4>
<form method="post">
<input type="email" name="email" placeholder="yourname@example.com" />
<input type="submit" value="Subscribe"/>
</form>
</div>

_Subscribe.cs.html.cs

public class _SubscribeModel : PageModel
{
public void OnGet()
{
}
public async Task<IActionResult> OnPostAsync(string email)
{
if (!ModelState.IsValid)
{
return Page();
}
await Task.Run(() =>
{
//do something
});
return RedirectToPage();
}
}

现在,部分视图正在主页中呈现。

Index.cshtml

@page
@model IndexModel
@{
ViewData["Title"] = "Welcome";
}
<h2>Hello, Welcome to my website!</h2>
<partial name="_Subscribe" model="Model.SubscribeModel" />

Index.cshtml.cs

public class IndexModel : PageModel
{
public IndexModel()
{
SubscribeModel = new _SubscribeModel();
}
public _SubscribeModel SubscribeModel { get; }
public void OnGet()
{
}
}

我做了一些研究,发现部分视图背后的代码并不像普通页面那样自动执行,这意味着我必须显式调用OnPost,但这似乎是错误的。

我做错什么了吗?

如有任何帮助,我们将不胜感激。

局部视图不应该有PageModel文件。它们本质上是被呈现到调用页面中并成为其中一部分的小部件。应该将OnPostAsync方法添加到调用页的PageModel类中。

最新更新