I want to call a JSON method on my textbox change event using jquery.
Below is how my JsonResult method looks like
public JsonResult GetUserName(string emailId)
{
string UserName = "";
var query = (from u in DbContext.Users
where u.User_Email.ToLower() == emailId.ToLower()
select u).SingleOrDefault();
if(query!=null)
{
UserName = query.User_FirstName +", "+query.User_LastName;
}
return Json(UserName, JsonRequestBehavior.AllowGet);
}
below is my view code
Email: <input type="text" id="txtEmail" /><br /><br />
Name: <input type="text" id="txtName" />
below is the jquery code
<script type="text/javascript">
$(document).ready(function () {
//$("#txtEmail").first().focus();
$("#txtEmail").change(function () {
var emailId = $(this).val();
//$("#txtName").val(emailId);
$.ajax({
url: 'GetUserName',
type: 'POST',
data: JSON.stringify({ emailId: emailId }),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
if (data != "" || data != null) {
$("#txtName").val(data);
}
else {
alert("Our system does not recognize this email. Please try again.");
$("#txtEmail").focus();
}
}
});
});
});
</script>
Note….My GetUserName JsonResult method belongs to my Default Controller.
My jquery code is successfully getting executed on change event but the GetUserName method doesn’t get called…please let me know what I am missing.
Thanks,
You url is wrong it should be like
/DefaultControllerName/GetUserName(it doesn’t matter that this is the default controller ifGetUserNameis not the default action you have to specify the contoller in the url) that’s why you should always use the built inUrlHelperto generate the urls in ASP.NET MVC:With the aspx viewengine: