json function not call via using jquery ajax mvc - javascript

I am using model pop-up and I want to call controller but json function not calling. when I use a breakpoint in jquery data fill in the textbox but function not call. kindly tell me where I am wrong.
first, I declare a variable then store password textbox value then pass password parameter then I click save and using breakpoint message show undefine and I remove previous code then I use this code its not calling function.
Javascript
<script>
function mSavePassword() {
$.ajax({
url: "#Url.Action("ChangePassword")",
type: "GET",
contentType: "application/json;charset=UTF-8",
data: {
Password: $('#txtcurrentpassword').val(),
NewPassword: $('#txtpassword').val(),
ConfirmPassword: $('#txtConformPassword').val()
},
dataType: "json",
success: function (Record) {
alert("Record Inserted Successfully");
},
});
}
</script>
JSON FUNCTION
public JsonResult ChangePassword(User U)
{
try
{
con = new SqlConnection(constring);
con.Open();
cmd = new SqlCommand("select User_password from BriskSecurity.dbo.Users where User_Id=" + Session["AgentID"] + "", con);
string mPwd = Convert.ToString(cmd.ExecuteScalar());
if (Cryptographer.Encrypt(U.Password.Trim()) != mPwd.Trim())
{
TempData["old"] = "Incorrect Password";
return Json(TempData["old"], JsonRequestBehavior.AllowGet);
}
if (U.NewPassword.Trim() != U.ConfirmPassword.Trim())
{
TempData["Wrong"] = "Your New Password and Confirm Password do not match";
return Json(TempData["Wrong"], JsonRequestBehavior.AllowGet);
}
U.ConfirmPassword = Cryptographer.Encrypt(U.ConfirmPassword);
cmd = new SqlCommand("update BriskSecurity.dbo.Users set User_password='" + U.ConfirmPassword + "' where User_ID=" + Session["AgentID"] + "", con);
cmd.ExecuteNonQuery();
con.Close();
TempData["PSuccess"] = "Your password has been changed successfully";
}
catch (Exception)
{
TempData["Error"] = "Password not changed due to an error Try Again";
return Json(TempData["Error"], JsonRequestBehavior.AllowGet);
throw;
}
return Json("", JsonRequestBehavior.AllowGet);
}

I would suggest way to send dynamic url to ajax javscript from C# MVC page.
I very easy to use a form like:
<form method="post" action="#Url.Action("ChangePassword")">
<input ... />
<input ..../>
<input type="submit" value="Change password" />
</form>
and with jQuery:
$("form").on("submit", function(e) {
mSavePassword($(this));
});
function mSavePassword($form) {
$.ajax({
url: $form.prop("action"),
type: $form.prop("method"),
data: {
Password: $('#txtcurrentpassword').val(),
NewPassword: $('#txtpassword').val(),
ConfirmPassword: $('#txtConformPassword').val()
},
dataType: "json",
success: function (record) {
alert("Record Inserted Successfully");
}
});
}
and do changes on server side:
[HttpPost]
public JsonResult ChangePassword(User U)
otherwise, won't work

Related

Asp.net controller recieving null

My ASP.net controller is receiving null instead of passed in parameters :(
Js function:
function SendFormToController() {
var username = document.getElementById("UsernameField").value;
var email = document.getElementById("EmailField").value;
var password = document.getElementById("PasswordField").value;
var SendJson = {
Username: username,
Email: email,
Password: password
};
console.log(JSON.stringify(SendJson));
$.ajax({
type: "POST",
data: JSON.stringify(SendJson),
url: "Register/Register",
contentType: "application/json"
});
}
Data is present when I console log it. But in the controller, I get - https://prnt.sc/u2mpa6
And it is for every field here
First; Did you add the [HttpPost] attribute on top of your controller method?
Second; If you submit it in 'querystring' format: Username=xx&Password=yy&... and use (HttpGet). Does that work?
If you need to do a POST (and not want to use GET) you can create an object with all your current arguments and use the [FromBody] attribute:
[Route("Register")]
[HttpPost]
public ResultData Register([FromBody] RegisterRequest data) {
//Your logic...
}
And client (JavaScript) side:
let url = 'http://...';
$.post(url, { Username: name, Password: pass, What: ever }, function (result) {
//Do some nice stuff
})
.fail(function (error) {
//Oh no! Show error.statusText
});

How to return invalid password error message via Ajax - MVC

I have login page where, user enter their Email and password , but i want display a alert or text like (you entered invalid password), when they enter wrong password. i already check Checkpass is not null do something and in else i dont know what should i do to be honest.Can anyone please help me or point me in the right direction!
Thanks in advance:)
Controller:
[HttpPost]
public JsonResult Login(string Mail, string pass)
{
var hashedPass = PasswordSecurity.PasswordStorage.CreateHash(pass);
using (DbNameSpace db = new DbNameSpace())
{
var query = from cbr in db.Contact_Business_Relation
join c in db.Contact on cbr.Contact_No_ equals c.Company_No_
join sa in db.Sales_Header on cbr.No_ equals sa.Sell_to_Customer_No_
join px in db.PX2 on c.E_Mail equals px.Email_ID
where c.E_Mail == Mail.ToLower()
select new
{
Mail = c.E_Mail,
pass = px.PS,
};
var user = query.FirstOrDefault();
var CheckPass = PasswordSecurity.PasswordStorage.VerifyPassword(pass, user.pass);
if (user != null && CheckPass) //Checkpassword
{
Session["Email"] = user.Mail.ToString();
}
else {
// ??
}
return Json(user, JsonRequestBehavior.AllowGet);
}
}
JavaScript:
<script>
$(document).ready(function () {
$("#login").click(function (e) {
var email = $("input[name=Mail]").val();
var password = $("input[name=pass]").val();
e.preventDefault();
$.ajax({
type: "POST",
dataType: "json",
url: '#Url.Action("Login", "Account")',
data: { Mail: email, pass: password },
success: function (status) {
if (status) {
window.location.href = "/Account/Index";
}
}
});
});
});
</script>
View:
<form autocomplete="on" class="login100-form validate-form">
<div>
<label>E-mail</label>
<div class="wrap-input100 validate-input" data-validate="Valid email is required: ex#abc.xyz">
<input class="input100" type="email" id="Email" name="Mail" placeholder="E-mail">
</div>
<label>Password</label>
<div class="wrap-input100 validate-input" data-validate="Password is required">
<input class="input100" type="password" id="Password" name="pass" placeholder="Kodeord">
</div>
<div id="invalidpassword"></div>
<div class="container-login100-form-btn">
<button id="login" class="login100-form-btn">
Log in
</button>
</div>
</form>
Check out this jquery tutorial. I personally would use the Fail and Done callback methods. Modify your c# controller to return different HTTP status codes. Use HTTP 200 when they pass a good username and password. Use HTTP 400 when they pass a bad password this should trigger the Fail() callback and allow you to alert on the failure.
https://learn.jquery.com/ajax/jquery-ajax-methods/
// Using the core $.ajax() method
$.ajax({
// The URL for the request
url: "post.php",
// The data to send (will be converted to a query string)
data: {
id: 123
},
// Whether this is a POST or GET request
type: "GET",
// The type of data we expect back
dataType : "json",
})
// Code to run if the request succeeds (is done);
// The response is passed to the function
.done(function( json ) {
$( "<h1>" ).text( json.title ).appendTo( "body" );
$( "<div class=\"content\">").html( json.html ).appendTo( "body" );
})
// Code to run if the request fails; the raw request and
// status codes are passed to the function
.fail(function( xhr, status, errorThrown )** {
alert( "Sorry, there was a problem!" );
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
})
// Code to run regardless of success or failure;
.always(function( xhr, status ) {
alert( "The request is complete!" );
});
The normal thing to do would be to set the response status to 401 and omit the usual data payload that would be sent with a successful response. Then it's up to the client code to recognize the error status and respond appropriately (e.g. perhaps by showing an alert and remaining on the name/password form); this client-side behavior would be specified in the $.ajax call.
It's an example. Hope to help, my friend.
[HttpPost]
public JsonResult Login(string Mail, string pass)
{
var status = true;
var hashedPass = PasswordSecurity.PasswordStorage.CreateHash(pass);
using (DbNameSpace db = new DbNameSpace())
{
var query = from cbr in db.Contact_Business_Relation
join c in db.Contact on cbr.Contact_No_ equals c.Company_No_
join sa in db.Sales_Header on cbr.No_ equals sa.Sell_to_Customer_No_
join px in db.PX2 on c.E_Mail equals px.Email_ID
where c.E_Mail == Mail.ToLower()
select new
{
Mail = c.E_Mail,
pass = px.PS,
};
var user = query.FirstOrDefault();
var CheckPass = PasswordSecurity.PasswordStorage.VerifyPassword(pass, user.pass);
if (user != null && CheckPass) //Checkpassword
{
Session["Email"] = user.Mail.ToString();
}
else {
status = false;
}
return Json(status, JsonRequestBehavior.AllowGet);
}
}
In Javascript:
<script>
$(document).ready(function () {
$("#login").click(function (e) {
var email = $("input[name=Mail]").val();
var password = $("input[name=pass]").val();
e.preventDefault();
$.ajax({
type: "POST",
dataType: "json",
url: '#Url.Action("Login", "Account")',
data: { Mail: email, pass: password },
success: function (status) {
if (status) {
window.location.href = "/Account/Index";
}else{
$('#invalidpassword').html('You have entered wrong password!');
}
}
});
});
});
</script>
This is how i end up to archive how to return invalid password error message , maybe it help someone on day :)
I created a enum to hold the values for MessageType:
public enum MessageType
{
Valid,
InvalidEmail,
InvalidUerNameAndPass,
}
and then i change my Controller to get different MessageType:
public JsonResult Login(string Mail, string pass)
{
MessageType messageType = MessageType.InvalidEmail;
using (DbNamesapce db = new DbNamesapce())
{
var query = // do Join
select new
{
//Select Something
};
var user = query.FirstOrDefault();
if (user == null)
{
return Json(new { messageType = MessageType.InvalidEmail }, JsonRequestBehavior.AllowGet);
}
if (user != null && CheckPass)
{
messageType = MessageType.Valid;
}
else
{
messageType = MessageType.InvalidUerNameAndPass;
}
return Json(new { messageType = messageType }, JsonRequestBehavior.AllowGet);
}
}
and i change my script to :
<script>
$(document).ready(function () {
$("#login").click(function (e) {
var email = $("input[name=Mail]").val();
var password = $("input[name=pass]").val();
e.preventDefault();
$.ajax({
type: "POST",
dataType: "json",
url: '#Url.Action("Login", "Account")',
data: { Mail: email, pass: password },
success: function (response) {
switch ($.trim(response.messageType))
{
case '#Convert.ToInt32(YourNAmeSpace.Models.MessageType.Valid)':
alert("Valid");
break;
case '#Convert.ToInt32(YourNAmeSpace.Models.MessageType.InvalidEmail)':
alert("InvalidUerNameAndPass");
break;
case '#Convert.ToInt32(YourNAmeSpace.Models.MessageType.InvalidUerNameAndPass)':
alert("InvalidUerNameAndPass");
break;
}
}
});
});
});
</script>

I'm using ajax call in ASP.NET application and I'm getting entire HTML page as response from jquery Ajax call

I'm developing an ASP.NET web application. Where in login screen I used jQuery Ajax call to connect server side code. In the response from the ajax call Im getting entire HTML page instead of true or false ( the actual result I want from the response).
Below is my server code.
[WebMethod]
public static string LoginValidation(string userName, string passWord)
{
string connectionString = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("select * from LoginUser where username = '"
+ userName + "' and password = '" + passWord + "'");
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
return "succes";
}
return "failure";
}
Below is my Jquery Ajax call.
$(document).ready(function () {
$('#txtLogin').focus();
});
$('#btnLogin').click(function () {
var username = $('#txtLogin').val();
var password = $('#txtPassword').val();
if (username === "" || password === "") {
alert('Both the fields are mandatory. Kindly try again');
$('#txtLogin').focus();
return;
}
else {
//ajax call to validate the login
$.ajax({
type: 'POST',
data: { 'userName': username, 'passWord': password },
url: 'Default.aspx/LoginValidation',
async: true,
datatype: 'text',
success: function (data) {
alert('test sadfadfa '+data+' '+data.responseText);
if (data == "failure") {
//redirecting to master page once after the successfull login
window.location.href = "/masterscreen.aspx";
}
else {
alert('false');
}
return;
},
error: function (data) {
}
});
//ajax call end
}
});
i've included the contentType in my Ajax call. It resolved my problem. Now, I'm getting JSON response as expected. Hope this helps some one.Thanks for those who helped me out.

Persist data across multiple controllers

I have a login form (created with Html.BeginForm()) with an email field, password field, and a "Forgot Password?" link within it. Originally, it was a submit button within the login form, and it would intercept the SignIn action. I wanted to abstract the Forgot Password functionality from the SignIn action.
In doing so, I noticed that it was set up this way in order to pass the email field value to the Forgot Password page (so the user wouldn't have to re-enter it). That was placed into TempData.
My thought was to have an AJAX call to a new controller action:
[HttpPost]
[AllowAnonymous]
public ActionResult ToForgotMyPassword(string email)
{
TempData["signInEmail"] = email;
return Json(new { redirectUrl = Url.Action("ForgotMyPassword"), TempData = TempData, email = email });
}
But my problem I've found is the TempData doesn't persist to the next action, ForgotMyPassword. On my view, I have the following JS:
$('#forgotPassword').click(function (e) {
var forgotMyPasswordUrl = $(this).attr('href');
e.preventDefault();
$.ajax({
type: "POST",
url: '#Url.Action("ToForgotMyPassword")',
data: { email: $('#Email').val() },
dataType: "json",
beforeSend: function (xhr) {
console.log(xhr);
},
success: function (result) {
//alert('Success');
console.log(result);
window.location = result.redirectUrl;
},
error: function (result) {
alert('Error');
console.log(result);
//window.location = forgotMyPasswordUrl;
}
});
});
How would I go about persisting this TempData to the redirect page? Is the way I'm going about this just not suited for an AJAX call? Should I just make a new model and new form within the Login form?
I tried to repeat your problem. And here what I done:
Controller:
[HttpPost]
[AllowAnonymous]
public ActionResult ToForgotMyPassword(string email)
{
TempData["signInEmail"] = email;
return Json(new { redirectUrl = Url.Action("ForgotMyPassword")});
}
[HttpGet]
[AllowAnonymous]
public ActionResult ForgotMyPassword()
{
var email = TempData["signInEmail"];
return View("Index", email);
}
View:
#model string
<html>
<head>
<title>#Model</title>
</head>
<body>
<div>
<input id="email" value="test#test.com"/>
<button id="forgotPassword">forgotPassword</button>
</div>
</body>
</html>
<script>
$('#forgotPassword').click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '#Url.Action("ToForgotMyPassword")',
data: { email: $('#email').val() },
dataType: "json",
beforeSend: function (xhr) {
console.log(xhr);
},
success: function (result) {
console.log(result);
window.location = result.redirectUrl;
},
error: function (result) {
alert('Error');
console.log(result);
}
});
});
</script>
And all this stuff works fine, so i checked two theories:
1) If you try to send TempData ("TempData = TempData" in next code fragment)
Json(new { redirectUrl = Url.Action("ForgotMyPassword"), TempData = TempData, email = email });
TempData will be cleared, it will not have any element in it's collection
2) if you input id="email" and in script you use $("#Email").val() - you will got nothing. name should be equals
I hope it helps.

Ajax call failing to get the return message from web api service

I am making a simple ajax call to the web api service that serves an authentication routine.
My problem is the ajax call can make a request to the service but errors out once the service returns a boolean value.
WHAT I WANT:
All i want to do is check if the returned boolean is true or false. If true i want to redirect the user to another page.
Could somebody please help me out on this?
JQUERY CODE:
<script type="text/javascript">
$(document).ready(function () {
$('#submitButton').click(function () {
var name = $(userNameTextBox).val);
var pass = $(passwordTextBox).val();
if (name.length == 0 || pass.length == 0) {
alert("Please enter your credentials");
}
else {
$.ajax({
url: "http://localhost:50503/api/Authentication/Authenticate",
data: { userName: name, passWord: pass },
cache: false,
type: 'GET',
dataType: 'json',
success: function (msg) {
alert(msg);
},
error: function (msg) {
alert("Error Message: "+msg);
}
});
}//end of else
});
});
</script>
Here is my webapi service
public class AuthenticationController : ApiController
{
[HttpGet]
[Route("api/Authentication/Authenticate")]
public bool Authenticate(string userName,string passWord)
{
if (userName.ToLower().Equals("username") && passWord.ToLower().Equals("password"))
{
return true;
}
else
{
return false;
}
}
}
You can try replace your ajax call by this maybe, remove the dataType:
var request = $.ajax({
url: "http://localhost:50503/api/Authentication/Authenticate",
cache: false,
type: 'POST',
data: { userName: userName, passWord: passWord }
});
request.done(function (msg) {
//check the boolean and redirect user to another page.
if(msg) window.location.href = "http://nextpage.com";
});
i also change the method to POST. More appropriate in your case.
If all else fails, put a debugger breakpoint (e.g., via the debugger directive in your error callback to $.ajax and run your code in the browser's debugger (i.e. Chrome dev tools). Then, after the breakpoint is hit, you should be able to determine (by walking the stack) why the error callback is invoked.
My Test
I've tried to reproduce your case, and for me it doesn't fail. I've defined a test controller in the following way:
using System.Web.Http;
namespace Test
{
public class TestController : ApiController
{
[HttpGet]
public bool Authenticate(string username, string password)
{
return username == "user" && password == "pass";
}
}
}
And I make an AJAX call to it from JavaScript like so:
$.ajax({url: 'http://localhost:59900/api/test', type: 'get', dataType: 'json', cache: false, data: { userName: 'user', passWord: 'pass' }}).done(function () {console.log("Success", arguments);}).fail(function () { console.log("Error", arguments); });
The AJAX call invokes the success callback (done) with true as its result, so no issues at all.
Parser Error
It appears that jQuery can't parse the JSON sent from Web API (true). To return valid JSON, return an object of the following type from your controller:
public class Result
{
public bool Result { get;set; }
}
This should result in the following JSON being sent to your client:
{ "Result": true }
Updated controller:
namespace Test
{
public class TestController : ApiController
{
[HttpGet]
public Result Authenticate(string username, string password)
{
return new Result { Result = username == "user" && password == "pass" };
}
}
}
Try to use (worked for me, check responseJSON.Message of first parameter object):
$.post(url, jsonData).
done(function (data) {}).
fail(function (xhr, status, err) {
alert("Error " + err + ". " + xhr.responseJSON.Message);
});

Categories

Resources