C# asp.net MVC 4 通过不同形式多次发布

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15788806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 17:58:06  来源:igfitidea点击:

asp.net MVC 4 multiple post via different forms

c#asp.net-mvcformshttp-post

提问by Davidred15

Right now I understand

现在我明白了

if (IsPost){   //do stuff }

checks all post methods on that page. However, I have 2 different forms posting 2 different information. These are a login form and a register form.

检查该页面上的所有发布方法。但是,我有 2 个不同的表单发布 2 个不同的信息。这些是登录表单和注册表单。

Is there a way I can check IsPost based on which form? For example,

有没有办法可以根据哪种形式检查 IsPost?例如,

if(Login.IsPost){ //do stuff }

but how would I define the Login variable? My form looks like:

但我将如何定义登录变量?我的表格看起来像:

<form id="Login" method = "POST">

I have tried:

我试过了:

var Login = Form.["Login"]

it did not work.

这没用。

I will appreciate any help.

我将不胜感激任何帮助。

Thanks.

谢谢。

采纳答案by jpshook

In an MVC view, you can have as many forms with as many fields as you need. To keep it simple, use a single view model with all the properties you need on the page for every form. Keep in mind that you will only have access to the form field data from the form that you submit. So, if you have a login form and registration form on the same page you would do it like this:

在 MVC 视图中,您可以根据需要拥有包含多个字段的多个表单。为简单起见,请使用单个视图模型,其中包含页面上每个表单所需的所有属性。请记住,您只能访问您提交的表单中的表单域数据。因此,如果您在同一页面上有登录表单和注册表单,您可以这样做:

LoginRegisterViewModel.cs

登录注册ViewModel.cs

public class LoginRegisterViewModel {
    public string LoginUsername { get; set; }
    public string LoginPassword { get; set; }

    public string RegisterUsername { get; set; }
    public string RegisterPassword { get; set; }
    public string RegisterFirstName { get; set; }
    public string RegisterLastName { get; set; }
}

YourViewName.cshtml

你的视图名称.cshtml

@model LoginRegisterViewModel

@using (Html.BeginForm("Login", "Member", FormMethod.Post, new {})) {

    @Html.LabelFor(m => m.LoginUsername)
    @Html.TextBoxFor(m => m.LoginUsername)

    @Html.LabelFor(m => m.LoginPassword)
    @Html.TextBoxFor(m => m.LoginPassword)

    <input type='Submit' value='Login' />

}

@using (Html.BeginForm("Register", "Member", FormMethod.Post, new {})) {

    @Html.LabelFor(m => m.RegisterFirstName)
    @Html.TextBoxFor(m => m.RegisterFirstName)

    @Html.LabelFor(m => m.RegisterLastName)
    @Html.TextBoxFor(m => m.RegisterLastName)

    @Html.LabelFor(m => m.RegisterUsername)
    @Html.TextBoxFor(m => m.RegisterUsername)

    @Html.LabelFor(m => m.RegisterPassword)
    @Html.TextBoxFor(m => m.RegisterPassword)

    <input type='Submit' value='Register' />

}

}

MemberController.cs

成员控制器.cs

[HttpGet]
public ActionResult LoginRegister() {
     LoginRegisterViewModel model = new LoginRegisterViewModel();
     return view("LoginRegister", model);
}

[HttpPost]
public ActionResult Login(LoginRegisterViewModel model) {
 //do your login code here
}

[HttpPost]
public ActionResult Register(LoginRegisterViewModel model) {
 //do your registration code here
}


Do not forget, when calling BeginForm, you pass the Controller name without "Controller" attached:

不要忘记,在调用 BeginForm 时,您传递的控制器名称没有附加“控制器”:

@using (Html.BeginForm("Login", "Member", FormMethod.Post, new {}))

instead of:

代替:

@using (Html.BeginForm("Login", "MemberController", FormMethod.Post, new {}))

回答by SLaks

You should make each <form>point to a separate action with its own model parameters.

您应该<form>使用自己的模型参数将每个点指向一个单独的操作。

回答by Dominic Sputo

使用此示例可防止在使用具有不同控制器操作的多个 Form Post 时进行不必要/意外的验证检查。


What to look for


要找什么

  • Essentially this code utilizes a Boolean inside of the Model to flag which Controller Action was called in the Form Post.
  • Notice the use of the nest model and the [Is Action Login] and [Is Action Register] Boolean properties that I set using the method helper IsActionLogin() and IsActionRegister(). Only one will be called in the respective Controller Action.
  • Notice the sReturnURL property in the model. This property stores previous navigation url and is shared with the both Login and Register Controller Actions. This will allow us to return to the page the user left off prior to having to log in.


    /* Begin Model logic */
    public class LoginRegisterModel
    {
        public LoginModel LoginModel { get; set; }
        public RegisterModel RegisterModel { get; set; }
        public string sReturnURL { get; set; }
        public bool bIsActionLogin { get; set; }
        public bool bIsActionRegister { get; set; }
        public void IsActionLogin()
        {
            bIsActionLogin = true;
            bIsActionRegister = false;
        }
        public void IsActionRegister()
        {
            bIsActionLogin = false;
            bIsActionRegister = true;
        }
    }
    
    public class LoginRegisterModel
    {
        public LoginModel LoginModel { get; set; }
        public RegisterModel RegisterModel { get; set; }
        public string sReturnURL { get; set; }
        public bool bIsActionLogin { get; set; }
        public bool bIsActionRegister { get; set; }
        public void IsActionLogin()
        {
            bIsActionLogin = true;
            bIsActionRegister = false;
        }
        public void IsActionRegister()
        {
            bIsActionLogin = false;
            bIsActionRegister = true;
        }
    }
    
    public class RegisterModel
    {
        [Required]
        [Display(Name = "Email")]
        [RegularExpression("^[a-zA-Z0-9_\.-]+@([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,6}$", ErrorMessage = "Email is not valid.")]
        public string UserName { get; set; }
    
        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }
    
        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Confirm Password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }
        /*End Model logic*/
    
        /*Begin Controller Logic*/
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginRegisterModel model, string sReturnURL)
        {
            model.IsActionLogin(); //flags that you are using Login Action
            //process your login logic here
        }
    
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Register(LoginRegisterModel model, string sReturnURL)
        {
            model.IsActionRegister(); //flag Action Register action
            //process your register logic here
        }
        /*End Controller Logic*/
    
    /*Begin View Logic*/
    @model eCommerce.Models.LoginRegisterModel
    @{  
        /*Place this view logic in both the Login.cshtml and Register.cshtml. Now use the last Action called as a Boolean check against your validation messages, so unnecessary validation messages don't show up.*/
        bool bLoginCallBack = Model.bIsActionLogin; 
        bool bRegisterCallBack = Model.bIsActionRegister;
        MvcHtmlString htmlIcoWarn = new MvcHtmlString(" font awesome icon here ");
        MvcHtmlString htmlIcoHand = new MvcHtmlString(" font awesome icon here ");
    }
    
        @using (Html.BeginForm("Login", "Account", new { sReturnURL = Model.sReturnURL }))
        {
            @Html.AntiForgeryToken()
            if (bLoginCallBack)
            {
                MvcHtmlString htmlLoginSummary = Html.ValidationSummary(true);
                if (!htmlLoginSummary.ToHtmlString().Contains("display:none"))
                {
                @:@(htmlIcoWarn)@(htmlLoginSummary)
                }
            }
            @Html.LabelFor(m => m.LoginModel.UserName)
            @Html.TextBoxFor(m => m.LoginModel.UserName, new { @placeholder = "Email" })
        @if (bLoginCallBack)
        {
            MvcHtmlString htmlLoginUsername = Html.ValidationMessageFor(m => m.LoginModel.UserName);
            if (!htmlLoginUsername.ToHtmlString().Contains("field-validation-valid"))
            {
            @:@(htmlIcoHand) @(htmlLoginUsername)
            }
        }
            @Html.LabelFor(m => m.LoginModel.Password)
            @Html.PasswordFor(m => m.LoginModel.Password, new { @placeholder = "Password" })
        @if (bLoginCallBack)
        {
            MvcHtmlString htmlLoginPassword = Html.ValidationMessageFor(m => m.LoginModel.Password);
            if (!htmlLoginPassword.ToHtmlString().Contains("field-validation-valid"))
            {
            @:@(htmlIcoHand) @(htmlLoginPassword)
            }
        }
                @Html.CheckBoxFor(m => m.LoginModel.RememberMe)
                @Html.LabelFor(m => m.LoginModel.RememberMe)
            <button type="submit" class="btn btn-default">Login</button>
        }
    @using (Html.BeginForm("Register", "Account", new { sReturnURL = Model.sReturnURL }))
    {
        @Html.AntiForgeryToken()
    
        if (bRegisterCallBack)
        {
            MvcHtmlString htmlRegisterSummary = Html.ValidationSummary(true);
            if (!htmlRegisterSummary.ToHtmlString().Contains("display:none"))
            {
                @:@(htmlIcoWarn)@(htmlRegisterSummary)
            }
        }
            @Html.LabelFor(m => m.RegisterModel.UserName)
            @Html.TextBoxFor(m => m.RegisterModel.UserName, new { @placeholder = "Email" })
        @if (bRegisterCallBack)
        {
            MvcHtmlString htmlRegisterUsername = Html.ValidationMessageFor(m => m.RegisterModel.UserName);
            if (!htmlRegisterUsername.ToHtmlString().Contains("field-validation-valid"))
            {
            @:@(htmlIcoHand) @(htmlRegisterUsername)
            }
        }
            @Html.LabelFor(m => m.RegisterModel.Password)
            @Html.PasswordFor(m => m.RegisterModel.Password, new { @placeholder = "Password" })
        @if (bRegisterCallBack)
        {
            MvcHtmlString htmlRegisterPassword = Html.ValidationMessageFor(m => m.RegisterModel.Password);
            if (!htmlRegisterPassword.ToHtmlString().Contains("field-validation-valid"))
            {
            @:@(htmlIcoHand) @(htmlRegisterPassword)
            }
        }
            @Html.LabelFor(m => m.RegisterModel.ConfirmPassword)        @Html.PasswordFor(m => m.RegisterModel.ConfirmPassword, new { @placeholder = "Confirm Password" })                
        @if (bRegisterCallBack)
        {
            MvcHtmlString htmlRegisterConfirmPassword = Html.ValidationMessageFor(m => m.RegisterModel.ConfirmPassword);
            if (!htmlRegisterConfirmPassword.ToHtmlString().Contains("field-validation-valid"))
            {
            @:@(htmlIcoHand) @(htmlRegisterConfirmPassword)
            }
            <button type="submit" class="btn btn-default">Signup</button>
        }
    }
    /*End View Logic*/
    
  • 本质上,此代码利用模型内部的布尔值来标记在 Form Post 中调用了哪个控制器操作。
  • 请注意嵌套模型的使用以及我使用方法助手 IsActionLogin() 和 IsActionRegister() 设置的 [Is Action Login] 和 [Is Action Register] 布尔属性。在相应的控制器操作中只会调用一个。
  • 请注意模型中的 sReturnURL 属性。此属性存储以前的导航 url,并与登录和注册控制器操作共享。这将允许我们返回到用户在必须登录之前离开的页面。


    /* Begin Model logic */
    public class LoginRegisterModel
    {
        public LoginModel LoginModel { get; set; }
        public RegisterModel RegisterModel { get; set; }
        public string sReturnURL { get; set; }
        public bool bIsActionLogin { get; set; }
        public bool bIsActionRegister { get; set; }
        public void IsActionLogin()
        {
            bIsActionLogin = true;
            bIsActionRegister = false;
        }
        public void IsActionRegister()
        {
            bIsActionLogin = false;
            bIsActionRegister = true;
        }
    }
    
    public class LoginRegisterModel
    {
        public LoginModel LoginModel { get; set; }
        public RegisterModel RegisterModel { get; set; }
        public string sReturnURL { get; set; }
        public bool bIsActionLogin { get; set; }
        public bool bIsActionRegister { get; set; }
        public void IsActionLogin()
        {
            bIsActionLogin = true;
            bIsActionRegister = false;
        }
        public void IsActionRegister()
        {
            bIsActionLogin = false;
            bIsActionRegister = true;
        }
    }
    
    public class RegisterModel
    {
        [Required]
        [Display(Name = "Email")]
        [RegularExpression("^[a-zA-Z0-9_\.-]+@([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,6}$", ErrorMessage = "Email is not valid.")]
        public string UserName { get; set; }
    
        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }
    
        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Confirm Password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }
        /*End Model logic*/
    
        /*Begin Controller Logic*/
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginRegisterModel model, string sReturnURL)
        {
            model.IsActionLogin(); //flags that you are using Login Action
            //process your login logic here
        }
    
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Register(LoginRegisterModel model, string sReturnURL)
        {
            model.IsActionRegister(); //flag Action Register action
            //process your register logic here
        }
        /*End Controller Logic*/
    
    /*Begin View Logic*/
    @model eCommerce.Models.LoginRegisterModel
    @{  
        /*Place this view logic in both the Login.cshtml and Register.cshtml. Now use the last Action called as a Boolean check against your validation messages, so unnecessary validation messages don't show up.*/
        bool bLoginCallBack = Model.bIsActionLogin; 
        bool bRegisterCallBack = Model.bIsActionRegister;
        MvcHtmlString htmlIcoWarn = new MvcHtmlString(" font awesome icon here ");
        MvcHtmlString htmlIcoHand = new MvcHtmlString(" font awesome icon here ");
    }
    
        @using (Html.BeginForm("Login", "Account", new { sReturnURL = Model.sReturnURL }))
        {
            @Html.AntiForgeryToken()
            if (bLoginCallBack)
            {
                MvcHtmlString htmlLoginSummary = Html.ValidationSummary(true);
                if (!htmlLoginSummary.ToHtmlString().Contains("display:none"))
                {
                @:@(htmlIcoWarn)@(htmlLoginSummary)
                }
            }
            @Html.LabelFor(m => m.LoginModel.UserName)
            @Html.TextBoxFor(m => m.LoginModel.UserName, new { @placeholder = "Email" })
        @if (bLoginCallBack)
        {
            MvcHtmlString htmlLoginUsername = Html.ValidationMessageFor(m => m.LoginModel.UserName);
            if (!htmlLoginUsername.ToHtmlString().Contains("field-validation-valid"))
            {
            @:@(htmlIcoHand) @(htmlLoginUsername)
            }
        }
            @Html.LabelFor(m => m.LoginModel.Password)
            @Html.PasswordFor(m => m.LoginModel.Password, new { @placeholder = "Password" })
        @if (bLoginCallBack)
        {
            MvcHtmlString htmlLoginPassword = Html.ValidationMessageFor(m => m.LoginModel.Password);
            if (!htmlLoginPassword.ToHtmlString().Contains("field-validation-valid"))
            {
            @:@(htmlIcoHand) @(htmlLoginPassword)
            }
        }
                @Html.CheckBoxFor(m => m.LoginModel.RememberMe)
                @Html.LabelFor(m => m.LoginModel.RememberMe)
            <button type="submit" class="btn btn-default">Login</button>
        }
    @using (Html.BeginForm("Register", "Account", new { sReturnURL = Model.sReturnURL }))
    {
        @Html.AntiForgeryToken()
    
        if (bRegisterCallBack)
        {
            MvcHtmlString htmlRegisterSummary = Html.ValidationSummary(true);
            if (!htmlRegisterSummary.ToHtmlString().Contains("display:none"))
            {
                @:@(htmlIcoWarn)@(htmlRegisterSummary)
            }
        }
            @Html.LabelFor(m => m.RegisterModel.UserName)
            @Html.TextBoxFor(m => m.RegisterModel.UserName, new { @placeholder = "Email" })
        @if (bRegisterCallBack)
        {
            MvcHtmlString htmlRegisterUsername = Html.ValidationMessageFor(m => m.RegisterModel.UserName);
            if (!htmlRegisterUsername.ToHtmlString().Contains("field-validation-valid"))
            {
            @:@(htmlIcoHand) @(htmlRegisterUsername)
            }
        }
            @Html.LabelFor(m => m.RegisterModel.Password)
            @Html.PasswordFor(m => m.RegisterModel.Password, new { @placeholder = "Password" })
        @if (bRegisterCallBack)
        {
            MvcHtmlString htmlRegisterPassword = Html.ValidationMessageFor(m => m.RegisterModel.Password);
            if (!htmlRegisterPassword.ToHtmlString().Contains("field-validation-valid"))
            {
            @:@(htmlIcoHand) @(htmlRegisterPassword)
            }
        }
            @Html.LabelFor(m => m.RegisterModel.ConfirmPassword)        @Html.PasswordFor(m => m.RegisterModel.ConfirmPassword, new { @placeholder = "Confirm Password" })                
        @if (bRegisterCallBack)
        {
            MvcHtmlString htmlRegisterConfirmPassword = Html.ValidationMessageFor(m => m.RegisterModel.ConfirmPassword);
            if (!htmlRegisterConfirmPassword.ToHtmlString().Contains("field-validation-valid"))
            {
            @:@(htmlIcoHand) @(htmlRegisterConfirmPassword)
            }
            <button type="submit" class="btn btn-default">Signup</button>
        }
    }
    /*End View Logic*/
    

回答by edtruant

I'd just load a partial view (containing a form) for each needed form, giving each partial a different viewmodel:

我只是为每个需要的表单加载一个局部视图(包含一个表单),给每个局部一个不同的视图模型:

  • Multiple-form-on-a-page-requirement: satisfied.
  • Javascript unobtrusive validation on each form: accomplished.
  • 页面上的多表单要求:满足。
  • 每个表单上的 Javascript 不显眼的验证:已完成。

回答by Biki

Instead of doing a form Submit, we can do a ajax post on click of corresponding submit button.

我们可以通过单击相应的提交按钮来执行 ajax 发布,而不是执行表单提交。

@using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { @Id = "Form1" }))
{

}

@using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { @Id = "Form2" }))
{

}

Once you allocate different id attribute to each of the form in your page, use code like this:

为页面中的每个表单分配不同的 id 属性后,请使用如下代码:

$(document).ready( function() {
  var form = $('#Form1');

 $('#1stButton').click(function (event) {

    $.ajax( {
      type: "POST",
      url: form.attr( 'action' ),
      data: form.serialize(),
      success: function( response ) {
        console.log( response );
      }
    } );
  } );
}

Repeat the same thing on 2nd Button click event to invoke the ajax post for the 2nd form.

在第二个按钮点击事件上重复同样的事情来调用第二个表单的 ajax 帖子。

This code uses .serialize() to pull out the relevant data from the form.

此代码使用 .serialize() 从表单中提取相关数据。

For future reference, the jQuery docsare very, very good.

为了将来参考,jQuery 文档非常非常好。

NB : The button you are using to trigger the event that causes the submit of the form via ajax post should not be of type submit! Else this will always fail.

注意:您用来触发导致通过 ajax post 提交表单的事件的按钮不应属于submit类型!否则这将永远失败。