对具有多个提交的表单进行建模和验证 [英] Modeling and validating a form with multiple submit

查看:98
本文介绍了对具有多个提交的表单进行建模和验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出使用ASP.Net Core 2对具有多个表单标签和多个提交按钮的表单进行建模和验证的正确方法.我所拥有的是一个表单,用户可以在其中输入用户名和密码,然后登录或输入他们的名字,姓氏和手机号码并注册.这是我的模型:

I am trying to figure out the proper way to model and validate a form with multiple form tags and multiple submit buttons using ASP.Net Core 2. What I have is a form where a user can either enter their username and password and sign in OR enter their first name, last name and cell number and sign up. Here is my model:

public class Landing
{
    [Required]
    public string Username { get; set; }
    [Required]
    public string Password { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    [Required]
    public string CellNumber { get; set; }
}

这是我相关的剃刀查看代码:

Here is my relevant razor view code:

@model MyApp.ViewModels.Landing

<form method="post">
    <div>
        <input asp-for="Username" type="text" />
    </div>
    <div>
        <input asp-for="Password" type="password" />
    </div>
    <div>
        <input type="submit" value="Sign In" />
    </div>
</form>

<form method="post">
    <div>
        <input asp-for="FirstName" type="text" />
    </div>
    <div>
        <input asp-for="LastName" type="text" />
    </div>
    <div>
        <input asp-for="CellNumber" type="text" />
    </div>
    <div>
        <input type="submit" value="Sign Up" />
    </div>
</form>

现在我遇到的问题是我的验证.因为我所有的字段都标记有[Required]属性,所以当我使用任一提交按钮提交表单时,它将验证所有5个字段.我想做的是仅在按下第一个提交按钮时验证UserNamePassword或在按下第二个提交按钮时仅验证FirstNameLastNameCellNumber.我该如何实现?

Now the problem I run into is with my validation. Because all my fields are marked with the [Required] attribute, when I submit the form using either submit button, it's validating all 5 fields. What I want to do is validate UserName and Password only, IF the first submit button is pushed OR validate FirstName, LastName and CellNumber only, IF the second submit button is pushed. How can I achieve this?

推荐答案

我将模型分成两个类,然后使用

I would break my models into two class and then use a ViewModel instead:

public class SignIn
{
    [Required]
    public string Username { get; set; }
    [Required]
    public string Password { get; set; }
}

public class SignUp
{
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    [Required]
    public string CellNumber { get; set; }
}

public class LandingViewModel
{
    public SignIn SignIn { get; set; }
    public SignUp SignUp { get; set; }
}

然后:

@model MyApp.ViewModels.LandingViewModel
SignIn.Username, SignIn.Password, SignUp.FirstName,...

这篇关于对具有多个提交的表单进行建模和验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆