watermelon_heart watermelon_heart - 1 year ago 91
jQuery Question

how to differentiate between two submit buttons

I am learning MVC and already working on a task that has become overwhelming, trying to figure out how to render a log in form from a partial view, inside a jQuery accordion tab, without submitting the entire page.

I am including an image of my page.

Your Order Tab
this is the page I am working on

Complete Order Tab
enter image description here

The first tab: "Your Order" contains on the right side a small log in form with a button that read "Sign In".

The fifth tab: "Complete Order" contains a button "Complete Order"

When I click the button on the first tab to Sign In, the code that executes is the code for Complete Order button, and that causes many errors, because all the information collected on subsequent tabs is not there as when Complete Order gets clicked.

I would like to ask for help, to figure out a way to separate the events of these buttons, and be able to do a log in without running code that is part of other event.

I am not sure how to approach to this, this is my first time working with this architecture.

If I could get help on how to execute the log in method, and just display a simple div displaying "success! that would help me a lot.

Thank you much!


The jQuery:

function ShoppingCartLogin() {
var userid = $("#YourOrder_MainLoginEmail").val();
//var userid = document.getElementById('UserName').value;
var password = $("#YourOrder_MainLoginPassword").val();
//var password = document.getElementById('Password').value;
var url = "/ShoppingCart/ShoppingCartLogin";
$("#btnLogin").val('Sign In');
url: url,
data: { userId: userid, pass: password },
cache: false,
type: "POST",
success: function (data) {
if (data == "1") {
alert("Successfull login.");
} else {
alert("Invalid user id and password.");
$(".YourOrder_MainLoginEmail").attr({ 'value': '' });
$(".YourOrder_MainLoginPassword").attr({ 'value': '' });
error: function (reponse) {
alert("error : " + reponse);
$("#btnlogin").val('Sign In');

The PartialView markup

<div class="YourOrder__inputEmail">
Html.TextBoxFor(m => m.UserName, new { @class = "YourOrder_MainLoginEmail", placeholder = "Email
Address", @id = "YourOrder_MainLoginEmail" })
Html.PasswordFor(m => m.Password, new { @class = "YourOrder_MainLoginPassword", placeholder =
"Password", @id = "YourOrder_MainLoginPassword" })

The controller code:

public ActionResult ShoppingCartLogin(LoginModel model, string returnUrl)
if (ModelState.IsValid)
using (Entities db = new Entities())
var user = (from u in db.Users where u.Email == model.UserName && u.Password == model.Password && u.IsActive select u).FirstOrDefault();

if (user == null)
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);

List<string> roles = new List<string>();
if (user.IsAdmin)
if (user.IsOrdersAdmin)
if (user.IsStoreAdmin)

user.LastLoginDate = DateTime.Now;

FormsAuthentication.SetAuthCookie(user.ID.ToString(), model.RememberMe);
var authTicket = new FormsAuthenticationTicket(
1, // version
user.ID.ToString(), // user name
DateTime.Now, // created
DateTime.Now.AddMinutes(90), // expires
model.RememberMe, // persistent?
string.Join(",", roles) // can be used to store roles

string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);


return RedirectToLocal(returnUrl);

// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);

When the code gets executed, LoginModel has null its propoerties UserName, Password although there are values in the textboxes.

The code goes to:

// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);

Answer Source

For separating two button, put two different id of two buttons, assume button id of tab 0( Your order) as btnYourOrder and tab 5(Complete order) button id as btnCompleteOrder then you write two jquery click events $("#btnYourOrder").click(function(){<Your Code>}); and $("#btnCompleteOrder").click(function(){<Your Code>}); and now whatever you want to execute you can put in their button events.

For executing partial view(not full postback) you can use below code

                url: <Your partial View URL>,
                type: "POST",
                contentType: 'text/html',
                success: function (data) {
                error: function (ex) {

divOrders--> Put one div with id divOrders where you want to show the partial view data.

If you want any other help or if you have not understood let me know, i will happy to help you.

Thanks Raviranjan

    Other options:
       Hi Nima: there are many options, Option 1: Change your controller method as 
        public ActionResult ShoppingCartLogin(LoginModel model, string returnUrl) 
          --> public ActionResult ShoppingCartLogin(string userId, string pass, string returnUrl) 
        for  your current javascript/juery ajax call .

        option 2: Put your User Id, Password, and button(no submit):  
        @using (Ajax.BeginForm("/ShoppingCartLogin", "ShoppingCart", new AjaxOptions { 
         UpdateTargetId =    "divSaveUsers", InsertionMode =InsertionMode.Replace, 
        OnSuccess = "onUserSaveSuccess", OnFailure = "onUserSaveFailure", HttpMethod = "POST" }, 
         new { @autocomplete = "off", @id = "frmuserdetails" }))
            @Html.ValidationSummary(true) <br/>
      <input type="button" value="Save" id="btnSaveData" /><br/>

        $("#btnSaveData").click(function (event) {


        and keep your controller method as usual
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download