Reputation: 35
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
Complete Order Tab
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!
CODE EDIT AFTER RECOMMENDATIONS
The jQuery:
function ShoppingCartLogin() {
$("#Email").val();
var userid = $("#YourOrder_MainLoginEmail").val();
//var userid = document.getElementById('UserName').value;
var password = $("#YourOrder_MainLoginPassword").val();
//var password = document.getElementById('Password').value;
alert(userid);
var url = "/ShoppingCart/ShoppingCartLogin";
$("#btnLogin").val('Sign In');
$.ajax({
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" })
</div>
<div>
<div>
Html.PasswordFor(m => m.Password, new { @class = "YourOrder_MainLoginPassword", placeholder =
"Password", @id = "YourOrder_MainLoginPassword" })
</div>
</div>
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)
{
roles.Add("Admin");
}
if (user.IsOrdersAdmin)
{
roles.Add("Orders");
}
if (user.IsStoreAdmin)
{
roles.Add("Stores");
}
user.LastLoginDate = DateTime.Now;
db.SaveChanges();
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);
HttpContext.Response.Cookies.Add(authCookie);
}
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);
Upvotes: 0
Views: 2006
Reputation: 565
i had two buttons generated by php code and i wanted to know which button is clicked. i used them in same class. The php code is as follow
$class = "qdiv";
$type="button";
$click="ask(".$j.")"; //put variable to have a record of question asked
echo '<button id="'.$j.'" type="'.$type.'" class="'.$class.'" onclick="'.$click.'">';
echo $row['question'];
echo '</button>';
In the code above i gave separate id but by some reason the id was not readable by JavaScript (one reason i guess is that i asked id by class and one class had different ids) so i have onclick=ask(j) function and j return a unique number to differentiate which button is clicked.
the java script code is as follow.
function ask(qid)
{
//var qid=document.getElementsByClassName("qdiv").id;
document.getElementById("divresult").innerHTML=qid;
}
Upvotes: 0
Reputation: 475
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
$.ajax(
{
url: <Your partial View URL>,
type: "POST",
contentType: 'text/html',
success: function (data) {
$("#divOrders").html(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" }))
{<br/>
@Html.AntiForgeryToken()<br/>
@Html.ValidationSummary(true) <br/>
<input type="button" value="Save" id="btnSaveData" /><br/>
}
<br/>
<script>
$("#btnSaveData").click(function (event) {
$("#frmuserdetails").submit();
});<br/>
</script>
and keep your controller method as usual
Upvotes: 3
Reputation: 1086
You can get button value in your post action argument by referencing button name,
For example if your button are defined like below,
<button type="submit" id="btnLogin" name="Command" value="Login">Login</button>
<button type="submit" id="btnCompleteOrder" name="Command" value="CompleteOrder">Complete Order</button>
you can get the button value and based on that choose which code you want to execute
[HttpPost]
public ActionResult PostAction(Model model,String Command)
{
If(Command == "Login")
//Send them to login screen
RedirectToAction("Login","LoginController");
Else If(Command == "CompleteOrder")
{
//Complete your order processing
}
Else
{
//Some default action
}
Return View("Index");
}
Upvotes: 1
Reputation: 818
Don't use submit, use <form action=''…
and declare a loginForm()
function to jQuery $.post
the credentials from those fields using a <button onclick='loginForm()'>Submit </button>
Upvotes: 0