简体   繁体   English

ASP .NET Core 5 Razor 页面:如何正确使用局部视图并验证它的 model Z9ED39E28EA931586B76A

[英]ASP .NET Core 5 Razor Pages: how to properly use Partial View and validate it's model state?

I'm using ASP .NET Core 5 Razor Pages.我正在使用 ASP .NET Core 5 Razor 页面。

My goal is to has a set of Partial Views (for reusability purpose) that I can use on several pages.我的目标是拥有一组可以在多个页面上使用的部分视图(出于可重用性目的)。 Each Partial View has a form with its own custom post event handler (it will be processed by a code-behind of a pages that will contain this Partial View).每个部分视图都有一个带有自己的自定义发布事件处理程序的表单(它将由包含此部分视图的页面的代码隐藏处理)。

NB Some pages can contain two or even more different Partial Views!注意:有些页面可能包含两个甚至更多不同的局部视图! And I need that Partial View models to be validated independently of each other (in two separate custom event handlers).而且我需要独立地验证部分视图模型(在两个单独的自定义事件处理程序中)。

Here is simplified code that I use for today.这是我今天使用的简化代码。 Partial View model (contains some data for a user):部分视图 model (包含用户的一些数据):

public partial class User
{
    [Required]
    public string Name { get; set; }
    [Required]
    public string Surname { get; set; }
}    

public class UserModel : PageModel
{
    [BindProperty]
    public User user { get; set; }
    [TempData]
    public string StatusMessage { get; set; }
    public UserModel()
    {
        user = new User();
    }
}

_UserPartial.cshtml (displays that user data): _UserPartial.cshtml (显示该用户数据):

@model UserModel

<div class="row text-warning">
    <div class="col-md-4">
        <form method="post" asp-page-handler="UserEdited">
            <div asp-validation-summary="ModelOnly"></div>
            <div class="form-group">
                <label asp-for="user.Surname" class="control-label"></label>
                <input asp-for="user.Surname" class="form-control" />
                <span asp-validation-for="user.Surname" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="user.Name" class="control-label"></label>
                <input asp-for="user.Name" class="form-control" />
                <span asp-validation-for="user.Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Save user data" />
            </div>
        </form>
    </div>
</div>

Index.cshtml (main page that contains Partial View): Index.cshtml (包含部分视图的主页):

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

@if (!String.IsNullOrWhiteSpace(@Model.StatusMessage))
{
    <div class="text-center">
        <h4 class="text-warning">@Model.StatusMessage</h4>
    </div>
}    

<div class="text-center" id="mainView">
    <p>Some text in a main view</p>
    <p>Some <a href="https://docs.microsoft.com/aspnet/core">link</a> in a main view.</p>
</div>

<div class="text-center" id="userPartialView">
    @{await Html.RenderPartialAsync("_UserPartial", IndexModel.userModel);}
</div>
//Some other Partial View (which contains some data for a message)
<div class="text-center" id="userPartialView">
    @{await Html.RenderPartialAsync("_MessagePartial", IndexModel.messageModel);}
</div>

Index.cshtml.cs (code-behind of a main page): Index.cshtml.cs (主页的代码隐藏):

public class IndexModel : PageModel
{
    public static UserModel userModel { get; set; }
    //A model for some other Partial View (which contains some data for a message)
    public static MessageModel messageModel { get; set; }
    [TempData]
    public string StatusMessage { get; set; }        

    public IActionResult OnGet()
    {
        userModel = new UserModel();
        messageModel = new MessageModel();
        return Page();
    }

    public IActionResult OnPostUserEdited()
    {
        if (!userModel.ModelState.IsValid)
        {
            return Page();
        }

        StatusMessage = "User data was saved!";
        return RedirectToPage();
    }
}

Problem is that userModel.ModelState is always valid even if Name and Surname are empty:问题是userModel.ModelState始终有效,即使NameSurname为空: 看起来 UserModel 根本没有验证 Looks like UserModel is not validaiting at all.看起来UserModel根本没有验证。

And I have a strong feeling that I'm using Partial Views tha wrong way (not the way they were supposed to be used).而且我有一种强烈的感觉,我正在以错误的方式使用部分视图(而不是他们应该使用的方式)。

So what's wrong with my code?那么我的代码有什么问题? How to properly use Partial View and validate it's model state?如何正确使用局部视图并验证它的 model state? Any help is appreciated.任何帮助表示赞赏。

You don't need to have a Page Model for the partial view.对于局部视图,您不需要页面 Model。 Just add it as a Razor View.只需将其添加为 Razor 视图即可。

在此处输入图像描述

Index.cshtml.cs索引.cshtml.cs

[BindProperty]
public User userModel { get; set; }

[BindProperty]
public Message messageModel { get; set; }

[TempData]
public string StatusMessage { get; set; }

public void OnGet()
{
    userModel = new User();
}

public IActionResult OnPostUserEdited()
{
    ModelState.Clear();
    if (!TryValidateModel(userModel))
    {
        return Page();
    }

    StatusMessage = "User data was saved!";
    return RedirectToPage();
}

public IActionResult OnPostMessageEdited()
{
    ModelState.Clear();
    if (!TryValidateModel(messageModel))
    {
        return Page();
    }

    StatusMessage = "Message data was saved!";
    return RedirectToPage();
}

Index.cshtml:索引.cshtml:

<div class="text-center" id="userPartialView">
    @{await Html.RenderPartialAsync("_UserPartial", Model.userModel);}
</div>

<div class="text-center" id="messagePartialView">
    @{await Html.RenderPartialAsync("_MessagePartial", Model.messageModel);}
</div>

在此处输入图像描述

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

相关问题 Asp .net Core:如何在Razor Pages的Partial View中使用模型? - Asp .net Core : How can I use a model inside a Partial View in Razor Pages? 如何在 ASP.NET Core Razor Pages 项目的 _layout.cshtml 文件中使用 Razor 页面使用实体框架作为部分视图? - How to use Razor Page Using Entity Framework as a partial view in _layout.cshtml file in ASP.NET Core Razor Pages project? ASP.NET 内核 Razor 页面,将 viewData 传递给部分视图 - ASP.NET Core Razor Pages, passing viewData to partial view 如何正确使用asp.net razor-pages 中的部分视图? - How to use partial views in asp.net razor-pages properly? 如何为 Razor Pages (.NET Core) 绑定视图模型? - How to bind view model for Razor Pages (.NET Core)? 后处理程序上的部分页面模型未执行 ASP.NET Core Razor Pages 2.0 - partial page model on post handler is not executing | ASP.NET Core Razor Pages 2.0 ASP.NET Core Razor页面模型状态无效且模型数据为空 - ASP.NET Core Razor Pages Model State Is Not Valid & Model data is empty Jquery Datatables样式在asp net core razor pages部分视图中不起作用 - Jquery Datatables style not working in asp net core razor pages partial view 在 asp.net 核心 razor 页面的部分视图中使用 forms - Using forms in partial views in asp.net core razor pages 如何在局部视图中使用不同的 model ASP.NET Core MVC - How to use a different model in partial view ASP.NET Core MVC
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM