加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-core-2.0 – 如何在Razor Pages中使用单独的BindPropert

发布时间:2020-12-16 06:40:36 所属栏目:asp.Net 来源:网络整理
导读:我正在使用带有Razor Pages的ASP.NET Core 2,我试图在一个页面上有两个具有单独属性(BindProperty)的表单. @page@model mfa.Web.Pages.TwoFormsModel@{ Layout = null;}form method="post" input asp-for="ProductName" / span asp-validation-for="ProductN
我正在使用带有Razor Pages的ASP.NET Core 2,我试图在一个页面上有两个具有单独属性(BindProperty)的表单.

@page
@model mfa.Web.Pages.TwoFormsModel
@{
    Layout = null;
}

<form method="post">
    <input asp-for="ProductName" />
    <span asp-validation-for="ProductName" class="text-danger"></span>
    <button type="submit" asp-page-handler="Product">Save product</button>
</form>

<form method="post">
    <input asp-for="MakerName" />
    <span asp-validation-for="MakerName" class="text-danger"></span>
    <button type="submit" asp-page-handler="Maker">Save maker</button>
</form>

和相应的PageModel:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;

namespace mfa.Web.Pages
{
    public class TwoFormsModel : PageModel
    {
        [BindProperty]
        [Required]
        public string ProductName { get; set; }

        [BindProperty]
        [Required]
        public string MakerName { get; set; }

        public async Task<IActionResult> OnPostProductAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }

            return Page();
        }

        public async Task<IActionResult> OnPostMakerAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }

            return Page();
        }
    }
}

点击两个提交按钮中的任何一个都会带我进入相应的帖子处理程序. “ProdutName”和“MakerName”都与我在相应输入字段中输入的内容完全一致地填充.到现在为止还挺好.

但是:ModelState.IsValid()始终返回true – 无论相应属性的值是否具有值.即使两个属性都为null,ModelState.IsValid()也为true.

另外:OnPostProductAsync()应仅验证“ProductName”,因此OnPostMakerAsync()应仅验证“MakerName”.

这可以完成吗?还是我从Razor Pages那里问了太多?有很多博客和教程向您展示如何在一个页面上有两个表单……但它们都使用相同的模型.我需要不同的型号!

解决方法

为了使验证正常工作,您必须创建一个包含两个属性的视图模型,并为要检查的每个属性定义[Required],但因为您有两个不同的表单,它们具有不同的验证,不能正常工作,因为如果两个值都被定义为必需,那么当您尝试验证产品时,它将验证Maker也没有值.

你能做的就是自己做检查.例如,OnPostProduct可以具有以下代码:

public async Task<IActionResult> OnPostProductAsync()
{
    if (string.IsNullOrEmpty(ProductName))
    {
        ModelState.AddModelError("ProductName","This field is a required field.");
        return Page();
    }

    // if you reach this point this means that you have data in ProductName in order to continue

    return Page();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读