【问题标题】:How to make your button on a form using asp.net-mvc work?如何使用 asp.net-mvc 使表单上的按钮起作用?
【发布时间】:2020-05-10 18:12:55
【问题描述】:

我有一个按钮,它似乎没有为我的数据库创建新用户。它的作用只是将用户验证继承到我的登录方法,需要一些指导,谢谢。以下是我正在尝试做的逻辑。如果数据库不存在,我想要做的我的创建按钮必须能够创建新用户。

    Controller:  
        [HttpPost]  
               [AllowAnonymous]  
               [ValidateAntiForgeryToken]  
               public ActionResult Create(CreateModel objSubmit)  
               {  
                   ViewBag.Msg = "Details submitted successfully";  

                   return View(objSubmit);  
               }  

       // This is for login, and its hits this method each time.  
        [HttpPost]  
               [AllowAnonymous]  
               [ValidateAntiForgeryToken]  
               public ActionResult Login(Login login)  
               {  
                   if (ModelState.IsValid)  
                   {  
                       bool success = WebSecurity.Login(login.username, login.password, false);  
                       var UserID = GetUserID_By_UserName(login.username);  
                       var LoginType = GetRoleBy_UserID(Convert.ToString(UserID));  

                       if (success == true)  
                       {  
                           if (string.IsNullOrEmpty(Convert.ToString(LoginType)))  
                           {  
                               ModelState.AddModelError("Error", "Rights to User are not Provide Contact to Admin");  
                               return View(login);  
                           }  
                           else  
                           {  
                               Session["Name"] = login.username;  
                               Session["UserID"] = UserID;  
                               Session["LoginType"] = LoginType;  

                               if (Roles.IsUserInRole(login.username, "Admin"))  
                               {  
                                   return RedirectToAction("AdminDashboard", "Dashboard");  
                               }  
                               else  
                               {  
                                   return RedirectToAction("UserDashboard", "Dashboard");  
                               }  

                           }  

                       }  
                       else  
                       {  
                           ModelState.AddModelError("Error", "Please enter valid Username and Password");  
                           return View(login);  
                       }  



                   }  
                   else  
                   {  
                       ModelState.AddModelError("Error", "Please enter Username and Password");  
                       return View(login);  
                   }  

               }  

       Model:  
       namespace eNtsaPortalWebsiteProject.Models  
       {  
           public class CreateModel  
           {  
               [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]  
               public string username { get; set; }  
           }  
       }  

       // View for login  
       <div data-="mainContent">
    <section class="container">
        <div class="logo col-sm-12 text-center col-md-12"> <img alt="" src="~/Images/eNtsa.png" /></div>
        <div class="clearfix"></div>

        <div class="container">
            <div class="row">

                <div id="MyWizard" class="formArea LRmargin">
                    @using (Html.BeginForm())
                    {
                        @Html.AntiForgeryToken()

                        <div id="divMessage" class="text-center col-md-12 col-md-offset-12 alert-success">
                            @Html.ValidationSummary()
                        </div>

                        <div class="col-md-12 col-md-offset-10 col-xs-12">
                            <div class="loginPage panel-info">
                                <div class="form-group"><span class=""><i class="glyphicon glyphicon-user">Username:</i></span>
                                    @Html.TextBoxFor(model => model.username, new { @class = "form-control text-center", autocomplete = "off" })
                                    @Html.ValidationMessageFor(model => model.username)
                                </div>




                                <div class="form-group">
                                    <span class=""><i class="glyphicon glyphicon-lock">Password:</i></span>
                                    @Html.PasswordFor(model => model.password, new { @class = "form-control text-center", autocomplete = "off" })
                                    @Html.ValidationMessageFor(model => model.password)
                                </div>
                            </div>

                            <div class="form-group">
                                <input id="BtnLogin" type="submit" class="btn btn-success btn-pressure" name="BtnLogin" value="Login" />
                                <input  type ="Submit" class="btn btn-info btn-pressure" name="BtnCreate" value="Create" />
                            </div>

                        </div>



                    }
                    <div class="clear"></div>
                </div>


            </div>


    </div>

</section>
</div>

       View for creating user:  
        <div class="mainContent">
<section class="container">

        <div class="logo col-sm-12 text-center col-md-10">
            <img alt="" src="~/Images/eNtsa.png"/>
        </div>
        <div class="container">

            @using (Html.BeginForm())
            {
                @Html.AntiForgeryToken()

                <div id="divMessage" class="text-center col-md-12 col-md-offset-12 alert-success">
                    @Html.ValidationSummary()
                </div>

                    <div class="col-md-12 col-md-offset-10 col-xs-12">
                        <div class="glyphicon-registration-mark">
                            <div class="form-group"><span class=""><i class="glyphicon glyphicon-user">Username:</i></span>
                                @Html.TextBoxFor(model=>model.username, new  {@class ="form-control text-center", automplete="off" })
                                @Html.ValidationMessageFor(model=>model.username)
                            </div>


                            <div class="form-group">
                                <span class=""><i class="glyphicon glyphicon-lock">Password:</i></span>
                                @Html.PasswordFor(model=>model.password, new {@class = "form-control text-center", autocomplete="off" })
                                @Html.ValidationMessageFor(model=>model.password)
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="col-md-offset-2 col-md-10">
                            <input type="submit" class="btn btn-success btn-pressure" name="BtnSubmit" value="Submit"/>
                        </div>
                    </div>


            }
        </div>
    </section>
</div>

【问题讨论】:

  • 不,我检查了表单中的所有标签。让我告诉你新的变化。但我仍然无法创建新用户。我认为我的控制器在这里工作不正常。它直接从登录方法(controller.cs)检查这些验证
  • 您是否在 Create 方法上设置了断点?是被击中了吗?如果您查看页面的来源,表单发布到哪里?
  • 嗨@Steve,请在屏幕截图上查看我的逻辑,它只命中登录方法。它不会转到我的 Create ActionResult 并返回 false。我来自 db 的 UserNamebyID 都是字符串而不是 int(primary-key)

标签: asp.net-mvc


【解决方案1】:

按钮正常工作 - 这不是您遇到的问题。

您可以有多个按钮来提交表单,但它们会返回到同一个地方,或者:

a) 在表单的“action”属性中指定的控制器/动作

b) 如果未指定任何操作,则为默认位置 - 在您的情况下,没有直接指定,因此它会回发到默认位置。

(见:How to link HTML5 form action to Controller ActionResult method in ASP.NET MVC 4

完成你想要做的最简单的方法是重构你的控制器并根据提交按钮的值来分支逻辑。

(见:MVC razor form with multiple different submit buttons?How to handle two submit buttons on MVC view)

这将需要对您编写的代码进行一些重构,但这是实现您想要做的最直接的方法。

用非常基本的术语来说,它看起来像这样:

型号:

   namespace eNtsaPortalWebsiteProject.Models  
   {  
       public class LoginCreateModel  
       {  
           [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]  
           public string username { get; set; }  

           public string btnSubmit { get; set; }   // both buttons will have the same name on your form, with different values ("Create" or "Login")
       }  
   }  

控制器:

    [HttpPost]  
    [AllowAnonymous]  
    [ValidateAntiForgeryToken]  
    public ActionResult Login(LoginCreateModel  objSubmit)  
    {  
         if (objSubmit.btnSubmit == "Create")
         {
             // Handle creation logic here
         }

         if (objSubmit.btnSubmit == "Login")
         {
              // Handle login logic here
         }



         return View(objSubmit);  
    }  

【讨论】:

  • 嗨@James S,我已经对我的控制器和模型进行了更改,我现在的体验是 UserId 为空,有一个具有 UserId 的过程。我可能会错过什么?
  • 这将取决于您所做的更改 - 如果没有更多信息,恐怕我无法告诉您。从您的原始屏幕截图中,我可以看到以下行:“var UserId = GetUserID_By_Username(login.username)” - 您是否检查过“login.username”是否正确传递?
  • 它没有正确传递,我正在调试它。成功为假,用户 ID 为空(数据类型为字符串)。我正在考虑从数据库中向该表中插入一些内容
  • 我的问题是关于“login.username”是否被传递给该方法。如果您不确定问题出在您的代码中还是数据库中,那么您可以尝试直接在您的数据库中运行 SQL 查询(尽管这更多的是一般的故障排除技巧,而不是您的问题的解决方案)。跨度>
  • login.username 确实通过了,只是 UserID 等字段为空
猜你喜欢
  • 2022-01-10
  • 2010-12-07
  • 1970-01-01
  • 1970-01-01
  • 2017-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-11
相关资源
最近更新 更多