26

今、私は理解しています

if (IsPost){   //do stuff }

そのページのすべての post メソッドをチェックします。ただし、2 つの異なる情報を投稿する 2 つの異なるフォームがあります。ログインフォームと登録フォームです。

どのフォームに基づいて IsPost を確認する方法はありますか? 例えば、

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

しかし、ログイン変数をどのように定義すればよいでしょうか? 私のフォームは次のようになります。

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

私が試してみました:

var Login = Form.["Login"]

それは動かなかった。

どんな助けにも感謝します。

ありがとう。

4

5 に答える 5

37

MVC ビューでは、必要な数のフィールドを持つフォームをいくつでも作成できます。シンプルにするために、すべてのフォームのページで必要なすべてのプロパティを備えた単一のビュー モデルを使用します。送信したフォームのフォーム フィールド データにのみアクセスできることに注意してください。したがって、同じページにログイン フォームと登録フォームがある場合は、次のようにします。

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
}

BeginForm を呼び出すときは、「Controller」を付けずにコントローラー名を渡すことを忘れないでください。

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

それ以外の:

@using (Html.BeginForm("Login", "MemberController", FormMethod.Post, new {}))
于 2013-04-04T12:49:22.630 に答える
3

それぞれ<form>のポイントは、独自のモデル パラメータを持つ個別のアクションに設定する必要があります。

于 2013-04-03T13:35:12.343 に答える
0
この例を使用して、異なるコントローラー アクションで複数のフォーム ポストを使用しているときに、不要または意図しない検証チェックを回避します。


何を探すべきか

  • 基本的に、このコードはモデル内のブール値を使用して、フォーム ポストで呼び出されたコントローラー アクションにフラグを立てます。
  • メソッド ヘルパー IsActionLogin() と IsActionRegister() を使用して設定した、ネスト モデルと [Is Action Login] および [Is Action Register] ブール型プロパティの使用に注目してください。それぞれのコントローラ アクションで呼び出されるのは 1 つだけです。
  • モデルの 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*/
    
于 2015-03-13T13:31:27.803 に答える