I have a table in my SQL Server database with columns
loginID, loginUser, loginPassword
Using Entity Framework, I want to check if a given record exists. I am using ASP.NET MVC with AJAX to send the data to my controller method.
$("#loginBtn").click(function () {
var loginUserRequest = $("#email").val();
var loginPassRequest = $("#pwd").val();
var loginTheUser = {
loginID: 1,
loginUser: loginUserRequest,
loginPassword: loginPassRequest
}
$.ajax({
type: "POST",
url: "Home/LoginUser",
data: loginTheUser
});
});
[HttpPost]
public ActionResult LoginUser(loginTable loginData)
{
WebEntities entit = new WebEntities();
var context = entit.loginTables.FirstOrDefault(lu => lu.loginUser == loginData.loginUser && lu.loginPassword == loginData.loginPassword);
if (context == null)
{
return View();
}
else
{
return RedirectToAction("Contact", "Home");
}
}
<form id="loginForm">
<div class="form-group">
<label>Username:</label>
<input type="text" class="form-control" id="email">
</div>
<div class="form-group">
<label>Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
<button id="loginBtn" type="submit" class="btn btn-default">Submit</button>
</form>
2
Answers
I am assuming the problem is that your
return view
andredirectToAction
are not working? You are making an Ajax call without without properly handling the result back to your ajax call.Try something like this. I didn’t test it, you might have to play around with it
The best way to do this is to make sure you take advantage of ajax fully. Return json result from your controller so that it will be easy to show any form of messages. Below is what you can do to get the best.
First, modify your javascript code like so:
As you can see from the ajax response, I am checking if response.error is true, that is I need to send that from the controller. Below is the modified controller action method:
I hope this helps.