asp.net MVC 4 multiple post via different forms

我是研究僧i 提交于 2019-11-26 06:33:58

问题


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.

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

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.


回答1:


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:

LoginRegisterViewModel.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

@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

[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:

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

instead of:

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



回答2:


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.



回答3:


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

@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:

$(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.

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

For future reference, the jQuery docs are very, very good.

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.




回答4:


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




回答5:


Use this example to prevent unnecessary/unintended validation checks while using multiple Form Post with different Controller Actions.


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*/
    


来源:https://stackoverflow.com/questions/15788806/asp-net-mvc-4-multiple-post-via-different-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!