简体   繁体   English

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

[英]partial page model on post handler is not executing | ASP.NET Core Razor Pages 2.0

I have a partial view with a page model. 我有一个页面模型的局部视图。 In the page model class I have the OnPost handler which is not being called when the form is submitted. 在页面模型类中,我拥有OnPost处理程序,该处理程序在提交表单时没有被调用。

_Subscribe.cshtml _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.cshtml.cs _Subscribe.cshtml.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();
        }
}

Now, the partial view is being rendered in the home page. 现在,部分视图正在主页中呈现。

Index.cshtml Index.cshtml

@page
@model IndexModel
@{
    ViewData["Title"] = "Welcome";
}

<h2>Hello, Welcome to my website!</h2>

<partial name="_Subscribe" model="Model.SubscribeModel" />

Index.cshtml.cs Index.cshtml.cs

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

        public _SubscribeModel SubscribeModel { get; }

        public void OnGet()
        {

        }
    }

I did some research and found out that the code behind partial views is not automatically executed like normal pages which means that I have to explicitly call OnPost but this seems wrong. 我做了一些研究,发现部分视图后面的代码不会像普通页面那样自动执行,这意味着我必须显式调用OnPost,但这似乎是错误的。

Am I doing something wrong? 难道我做错了什么?

Any help would be appreciated. 任何帮助,将不胜感激。

Partial Views should not have PageModel files. 部分视图不应包含PageModel文件。 They are essentially widgets that get rendered into the calling page and become part of that. 它们本质上是小部件,它们呈现到调用页面中并成为其中的一部分。 Your OnPostAsync method should be added to the PageModel class of the calling page. 您的OnPostAsync方法应添加到调用页面的PageModel类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM