0

enter image description hereenter image description hereI have a button, it does not seem to create new users to my database. What it does it only inherits user validaton to my Login method and need some guidance to this please and thanks. Below is the logic what i am trying to do. What i want to do my create button must be able to create new users if not exist to the database.

    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>
  • You are missing the form tag. https://www.completecsharptutorial.com/asp-net-mvc5/4-ways-to-create-form-in-asp-net-mvc.php – Steve Jan 24 '20 at 12:15
  • No i checked all my tags from the form. Let me show you new changes. But i am still not able to create new users. I think my controller is not working well here. it checks these validation directly from the login method(controller.cs) – eNtsa2019 Mkontwana Jan 24 '20 at 12:31
  • Have you put a breakpoint on the Create method? Is it being hit? If you view the source of the page, where is the form posting to? – Steve Jan 24 '20 at 13:54
  • Hi@Steve please see my logic on the screen shot, it only hits the login method. It does not go to my Create ActionResult and return false. Both my UserNamebyID from db are string not int(primary-key) – eNtsa2019 Mkontwana Jan 24 '20 at 14:02

1 Answers1

0

The button is working - that isn't the problem that you're having.

You can have multiple buttons to submit the form but they will return to the same place, either:

a) the controller/action specified in the "action" property of the form

b) if no action is specified then the default location - in your case there isn't one directly specified so it is posting back to the default location.

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

The easiest way to accomplish what you're trying to do would be refactor your controller and branch the logic depending on what the value is of the submit button.

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

This will require some refactoring of the code that you have written, but it is the most straightforward way of achieving what you're trying to do.

In very basic terms it would look something like this:

Model:

   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")
       }  
   }  

Controller:

    [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
  • 171
  • 1
  • 6
  • Hi@James S, i have made changes to my Controller and Model, what i am experience now UserId is null, have a procedure that has UserId. What could i be missing? – eNtsa2019 Mkontwana Jan 27 '20 at 07:01
  • That would depend on the changes that you've made - I'm afraid I can't tell you without more information. From your original screenshot I can see the following line: "var UserId = GetUserID_By_Username(login.username)" - have you checked that "login.username" is being passed correctly? – James S Jan 27 '20 at 13:31
  • its not passed correctly, im debugging it. success is false and UserID is null(data-type is string). Im thinking of doing some insert into that table from the database – eNtsa2019 Mkontwana Jan 27 '20 at 13:36
  • my question was about whether the "login.username" was being passed to the method. If you're not sure whether the issue is in your code or the database, then you could try running the SQL query in your database directly (although that's more of a general troubleshooting tip, rather than a solution to your problem). – James S Jan 27 '20 at 13:44
  • login.username does goes through, just fields like UserID is empty – eNtsa2019 Mkontwana Jan 27 '20 at 13:48