whole page gets refresh instead of div on login action - asp.net-mvc

I have 1 home page on which I have one anchor tag that is Login. On click, the Login anchor tag opens one pop up on the same home page like shown in the image below:
Now I want to perform the login action when the sign in button is clicked but only this pop up portion should get refresh and not the whole home page.
Currently, what is happening is my whole home page gets refreshed when the user enters the wrong EmailId or Password.
This is my View:
<div id="loginBox">
#using (Html.BeginForm("Login", "Account", FormMethod.Post, new { id = "loginForm" }))
{
<fieldset id="body">
<fieldset>
<label for="email">Email Address</label>
#Html.TextBox("Email", null, new { name = "email", id = "email" })
</fieldset>
<fieldset>
<label for="password">Password</label>
#Html.Password("Password", null, new { name = "password", id = "password" })
</fieldset>
<input onclick="Login()" type="submit" id="login" value="Sign in">
<label for="checkbox">
<input type="checkbox" id="checkbox">
<i>Remember me</i>
</label>
</fieldset>
}
</div>
This is my Login Javascript method to post my form and call controller method:
function Login() {
alert("ok");
var email = $("#email").val();
var password = $("#password").val();
$.post("/Account/Login", { Email: email, Password: password },
function (data) {
if (data == true) {
$("#LoginErrorMsg").hide();
} else {
$("#LoginErrorMsg").show();
}
});
}
Controller:
public JsonResult Login(string Email, string Password)
{
//Logic for login action
if(Emailid && Password is correct)
return Json(true);
else
return Json(false);
}
But here the problem is my controller method is not calling and when it is calling the whole page gets refresh even if the password is incorrect.
So can anybody help me?

Related

Assign authority to a user without user input when updating user profile

I've created a form that a user updates to update his profile. When I update the details of the user, and I log out and log in again, I get access denied. I found out that the reason for this was with the authority, every time I updated the table, other details were saved, but the authority is lost and as a result, access is denied.
So I would like to assign the role again within the form but without the user having any input. Any advise on how to implement that is appreciated.
below is my gsp;
<div class="form-group">
<label class="col-sm-5 control-label">
Roles
</label>
<div class="col-sm-5 ">
<g:each in="${roles}" var="role" status="i">
<div class="checkbox-inline">
<g:checkBox name="roles" value="${role.id}"
checked="${role.authority == "ROLE_MEMBER" ? 'true': user.hasRole(role)}"/>
<label for="roles[${i}]">${role.authority}</label>
</div>
</g:each>
</div>
</div>
<div class="form-group">
<div class="${hasErrors(bean: user, field: 'natureOfIndividual', 'error')} required">
<label for="natureOfIndividual" class="col-sm-5 control-label">
<g:message code="user.natureOfIndividual.label" default="Nature of Individual"/>
</label>
<div class="col-sm-5">
<g:select name="natureOfIndividual"
from="${['Local', 'Foreign']}"
class="form-control" noSelection="['': '-----Select-----']"
value="${user?.natureOfIndividual}"/>
</div>
</div>
</div>
With this code am not able to see the checkboxes. Still finding out why. But ultimately, I don't want the user to see any checkboxes, I want to assign the authority without his/her input.
I got a solution. In my UserController.groovy, there was updateRoles method that was called in update method. I commented out the method call. And now the roles are not affected after an update. Below is the code;
#Transactional
def update(User user) {
if (user == null) {
transactionStatus.setRollbackOnly()
notFound()
return
}
if (user.hasErrors()) {
transactionStatus.setRollbackOnly()
respond user.errors, view: 'edit'
return
}
boolean passChange = false
if (user.isDirty('password')) {
passChange = true
}
user.save flush: true
//updateRoles(user)
request.withFormat {
form multipartForm {
if (passChange) {
flash.message = "A user with username '${params.username}' and password '${params.password}' has been Updated"
} else {
flash.message = "Your profile has been updated"
}
redirect user
}
'*' { respond user, [status: OK] }
}
}
private updateRoles(User user) {
UserRole.removeAll(user)
List roleIds = params.roles instanceof String ? [params.roles] : params.roles
roleIds?.each { roleId ->
def role = Role.get(roleId)
UserRole.create(user, role, true)
}
}
As you've seen, I have commented out the method call in the update method. So when users update their details, their authorization is still preserved.

Trying to access html element in a view from controller in mvc

I am trying to access html element of a view from Controller in asp.net Mvc.
In login form after filling data in username and password textbox. Posting it through Http Post and accessing it in controller and now based on condition in controller i want to manipulate html element in same view from where it is getting data.
view
<span id="spanInvalidCredentialsMessage" style="display:none">
<div class="row form-group">
<div class="col-md-8 col-md-offset-2 text-danger">
Your credentials could not be authenticated. Please try again.
</div>
</div>
<div class="row form-group">
<div class="col-md-8 col-md-offset-2">
<hr class="alert-danger" />
</div>
</div>
</span>
login form field in view
<div class="col-md-8 col-md-offset-2">
<span class="glyphicon glyphicon-user text-primary">
</span>Username
</div>
<div class="col-md-8 col-md-offset-2">
#Html.TextBox("txtBxUsername", null, new { #class = "form-control" })
#Html.TextBox("txtBxPassword", null, new { #class = "form-control" })
<input id="btnLogin" type="submit" value="Login" class="btn btn-primary btn-block" />
</div>
Controller section getting login details through httppost
[HttpPost]
public ActionResult Login(FormCollection form)
{
//Invoke the method to authenticate the user credentials. txtBxUsername.Text.Trim().ToUpper()
string msgUserAuthenticated=objADService.GenericIsAuthenticatedWithMessage("ABC", form["txtBxUsername"].ToString().Trim().ToUpper(),form["txtBxPassword"].ToString());
//Check if the user was authenticated.
if (msgUserAuthenticated.Equals("Authenticated", StringComparison.InvariantCultureIgnoreCase) == true)
{
//Set the Session Variable and Redirect to the Home Page ASPX.
Session[CommonConstants.SESSION_USER_ID] = form["txtBxUsername"].ToString().Trim().ToUpper();
Session[CommonConstants.SESSION_USER_DOMAIN] = form["txtBxPassword"].ToString();
//Redirect the user to the home page
//Response.Redirect("Home.aspx");
return View("Home");
}
else
{
//Show the error message.
spanInvalidCredentialsMessage.Visible = true;
//Clear the text boxes for Username and Password.
txtBxUsername.Text = "";
txtBxPassword.Text = "";
return View("Login");
}
}
Expected if wrong username & password would be there then in controller i can access html element id in view and display it.
actual
no idea how to achieve

Prevent Modal Closing on form submit in Mvc

Is there a way to prevent the modal from closing when a form is submitted?
I am working on Email Sending Modal But When Click On Submit Button Controller Returns View, How To Prevent This ?
Modal Code Here:
#using (#Html.BeginForm("SendEmail", "Home", FormMethod.Post, new { #id = "form1", #enctype = "multipart/form-data" }))
{
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<span class="btn green fileinput-button">
<i class="fa fa-plus fa fa-white"></i>
<span >Attachment</span>
<input type="file" multiple="multiple" name="files" id="file">
</span>
<button class="btn btn-send" type="submit" >Send</button>
#ViewBag.Message
<br />
</div>
</div>
}
Here is Email Controller Code:
public ActionResult SendEmail(EmailContent emailContent, List<HttpPostedFileBase> files)
{
ViewBag.Message = "Email Sent Successfully!";
return RedirectToAction("Index","Home");
}
catch
{
ViewBag.Project = new SelectList(db.employees, "employee_id", "name");
ViewBag.Message = "Failed to Send Email, Please Try Again";
return RedirectToAction("Index","Home");
}
}
}
Please Help i want return no view , modal still open.

Action in controller received empty model from Html.BeginForm - ASP.NET MVC

I have stucked for 3 days. There is nowhere I had been looking for this problem. When I submit the form, Controller action method doesnt get the model.
My base view Login.cshtml
#{
string durum = ViewBag.Style;
switch (durum)
{
case "Login":
Html.RenderAction("_Login", "Dashboard");
break;
case "LostPassword":
Html.RenderAction("_LostPassword", "Dashboard");
break;
case "RegisterForm":
Html.RenderAction("_RegisterForm", "Dashboard");
break;
default:
Html.RenderAction("_Login", "Dashboard");
break;
}
}
One of my partial view _LostPassword.cshtml
#model HaberSitesi._Entities.Kullanici
#using (Html.BeginForm("LostPassword", "Dashboard", FormMethod.Post, new { #class = "forget-form", #style = "display:block" }))
{
if (TempData["ForgotPassword"] != null)
{
<div class="alert alert-warning ">
<button class="close" data-close="alert"></button>
<span>#TempData["ForgotPassword"]</span>
</div>
}
<h3>Şifrenizi mi unuttunuz ?</h3>
<p> Şifrenizi almak için lütfen E-Posta adresinizi giriniz. </p>
<div class="form-group">
<div class="input-icon">
<i class="fa fa-envelope"></i>
#Html.TextBoxFor(x => x.EPosta, new { #class = "form-control placeholder-no-fix", #type = "email", #autocomplete = "off", #placeholder = "Eposta", Name = "email" })
#Html.ValidationMessageFor(x => x.EPosta)
</div>
</div>
<div class="form-actions">
#Html.ActionLink("Geri Dön", "Login", "Dashboard", new { }, new { #type = "button", #id = "back-btn", #class = "btn grey-salsa btn-outline" })
<button type="submit" class="btn green pull-right"> Gönder </button>
</div>
}
And the action in controller DashboardController.cs
public ActionResult LostPassword()
{
VeriTransfer();
return View("Login");
}
[HttpPost]
public ActionResult LostPassword(Kullanici kullanici)
{
string kullaniciEposta = kullanici.EPosta;
Kullanici user = _kullaniciBll.Get(kullaniciEposta);
if (user != null)
{
TempData["ForgotPassword"] = "Şifreniz e-posta adresinize gönderildi.";
}
else
{
TempData["ForgotPassword"] = "Kayıtlarımızda e-posta adresiniz bulunamadı";
}
VeriTransfer();
return View("Login");
}
When I click submit button, I cant get any data (Kullanici kullanici) in controller. Every property comes null or default data value from model.
Note: Maybe my codes could have some other mistakes which are irrelevant with my problem. I just wonder why I get empty model. Thanks at least you have read my problem.
Your property is called EPosta but you changed the name of it to Name="email".So when the POST action happens it sends a property called email to the controller action and your Kullanici object expects a property called EPosta
Both of these will fix your problem:
Change Name="email" to Name="EPosta" or
Remove Name="email" completely
But like Stephen said it's better to remove it completely,because if you rename your property to EPosta2 in future and forget to change the name to Name="EPosta2" your POST will no longer work

jQuery Mobile: Injected content appears then disappears immediately

I have a login page using jQuery Mobile which contains the following code:
<div id="loginPage" data-role="page" data-theme="a">
<div data-role="content">
<div id="alerts"></div>
<form id="login-form">
<input type="text" id="username" name="username" value="" placeholder="username or email" />
<input type="password" id="password" name="password" value="" placeholder="password" />
<button id="login-button" onClick="userLogin()">Login</button>
</form>
</div><!-- /content -->
</div><!-- /page -->
Here is a part of my javascript that is called when the user clicks the 'Login' button. If one of the fields is left blank, I see the following text injected into the #alerts div, but then within a fraction of a second the content has disappeared again.
if (username.length == 0 || password.length == 0) {
//alert('Please enter your username or email and your password');
$('#alerts').html('Please enter your username or email and your password.').trigger('create');
}
I also tried this using .append() instead of .html(). Same result with both. I've commented out my test alert(), which works when one of the fields is left blank.
What can I do to make sure the content remains on the page once it is injected?
Thank you for any help or insight you can offer! -Mark
Per Jasper's request, here is all of the javascript that is executed when the 'Login' button is clicked:
function userLogin() {
var username = $("#username").val();
var password = $("#password").val();
if (username.length == 0 || password.length == 0) {
$('#alerts').append('Please enter your username or email and your password.').trigger('create');
}
else {
$.post("services/user-status.php", { type: 'login', username: username, password: password },
function(data) {
var response = data.item;
console.log(response);
if (response.loggedIn == false) {
$('#alerts').html('The username/email and password you used did not work. Please try again.').trigger('create');
}
else {
localStorage.userID = response.userID;
localStorage.username = response.username;
localStorage.userStatus = 'loggedIn';
$.mobile.changePage('profile.html');
}
},'json');
}
}
It looks like you need to stop the propagation of the click event from firing for your button. You can do that by returning false in the click event handler:
HTML --
<button id="login-button" onClick="return userLogin()">Login</button>
JS --
function userLogin() {
...
return false;
}​
Here is a demo: http://jsfiddle.net/BkMEB/3/
Also, since you are using jQuery, you can bind to the <button> element like this:
$('#login-button').bind('click', userLogin);
This is the same as putting onClick="return userLogin()" as an attribute of the button but allows you to remove your inline JS.
Here is a demo: http://jsfiddle.net/BkMEB/4/

Resources