I call the Ajax to get the result from web API in my MVC project. in my local the page works but in production it is not working and giving me this error in .js file exactly at this line: $.ajax
http://mylink.cloudapp.azure.com/searchuser 404 (Not Found)
x.extend.ajax anonymous function
This is my .js file:
$(document).ready(function () {
$('#btnSearch').click(function (evt) {
// debugger;
if (ValidateInput()) {
var data = {
LastName: $.trim($('#LastName').val() || ''),
Zip: $.trim($('#Zip').val() || ''),
Ssn: $.trim($('#Ssn').val() || '')
};
var token = $('[name=__RequestVerificationToken]').val();
$.ajax({
dataType: "json",
//headers: { "__RequestVerificationToken": token },
data: data,
url: '/searchuser',
type: 'POST',
cache: false,
success: function (result) {
console.log(result);
if (result && result.success) {
$('#ApplicationId').val(result.data.applicantId);
if (result.data.exception == null) {
$('#stepTwo').show();
$('#EmailAddress').val(result.data.userEmailAddress);
}
else {
$('#txtareaResponse').val(result.data.exception);
}
}
},
error: function () { debugger; alert('failure'); }
});
}
});
and this is top of my view:
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<link href="~/Content/Loan.css" rel="stylesheet" />
<script src="~/Scripts/Verify.js"></script>
and this is the controller method:
[AllowAnonymous]
[Route("searchuser")]
[HttpPost]
public async Task<ActionResult> SearchUser(UserInfo userInfo)
{
object userObject = null;
if (userInfo.LastName != null && userInfo.Zip != null && userInfo.Ssn != null)
{
string accessKey = CreateAccountKey(userInfo.LastName, userInfo.Zip, userInfo.Ssn);
UserKey userKey = new UserKey();
userKey.AccountKey = accessKey;
//var response = await httpClient.GetAsync(string.Format("{0}{1}/{2}", LoanApiBaseUrlValue, "/verifyuser", accessKey));
var response = await httpClient.PostAsJsonAsync(string.Format("{0}{1}", LoanApiBaseUrlValue, "/verifyuser"), userKey);
if (response.IsSuccessStatusCode)
{
userObject = new JavaScriptSerializer().DeserializeObject(response.Content.ReadAsStringAsync().Result) as object;
var json = response.Content.ReadAsStringAsync().Result;
var userVerify = new JavaScriptSerializer().Deserialize<VerifyUser>(json);
}
}
var respone = new
{
success = userObject != null,
data = userObject
};
return Json(respone, JsonRequestBehavior.AllowGet);
}
Try just returning an ActionResult
[AllowAnonymous]
[Route("searchuser")]
[HttpPost]
public ActionResult SearchUser(..){..}
also in your ajax call use the Razor syntax
$.ajax({
url: "#Url.Action("method", "Controller")",
type: "GET",
data: {},
success: function (data) {
//do stuff...
}
});
Related
I have a button in my view that calls a jQuery Ajax function passing in parameters from my model
<input type="button" value="Run Check" onclick="runCheck('#actionItem.StepID', '#Model.Client.DatabaseConnectionString', '#Model.Client.ClientID')" />
The jQuery function
<script type="text/javascript">
function runCheck(x, y, z) {
$.ajax({
url: '#Url.Action("ProcessFeedbackHasRows", "Client")',
type: 'POST',
contentType: 'application/json;',
data: { stepId: x, databaseConnectionString: y, clientId: z },
success: function (data) {
if (data.IsValid) {
//alert('true');
var url = '#Url.Action("ViewProcessingFeedBackPartial", "Client")';
$("#processingFeedbackPartialDiv").load(url, { stepId, databaseConnectionString, clientId },
function () {
$("#confirmButton").removeAttr("style");
});
} else {
//alert('false');
var newUrl = '#Url.Action("Processing", "Client")';
window.location = newUrl;
}
}
});
};
</script>
And finally my controller action
public JsonResult ProcessFeedbackHasRows(int StepId, string DatabaseConnectionString, int ClientID)
{
bool isValid = true;
FeedbackDetails feedbackDetails = new FeedbackDetails();
feedbackDetails.Data = _clientProcessingService.GetProcessingFeedbackDetails(StepId, DatabaseConnectionString);
if (feedbackDetails.Data.Rows.Count == 0)
{
_clientProcessingService.RunProcessStepConfirmation(DatabaseConnectionString, StepId, ClientID, "No information returned, automatically proceeding to next step.");
isValid = false;
}
return Json(new { IsValid = isValid });
}
The logic in the ajax function works when I hard code specific values in the controller to represent the appropriate step, client & database but when I debug I see the two integers as 0 and the string as null.
How can I pass these values to the controller? I considered just storing them in ViewBag or ViewData but that seems clunky and not really a good practice.
Try this,
var req={ stepId: x, databaseConnectionString: y, clientId: z }
function runCheck(x, y, z) {
$.ajax({
url: '#Url.Action("ProcessFeedbackHasRows", "Client")',
type: 'POST',
contentType: 'application/json;',
data: JSON.stringify(req),
success: function (data) {
if (data.IsValid) {
//alert('true');
var url = '#Url.Action("ViewProcessingFeedBackPartial", "Client")';
$("#processingFeedbackPartialDiv").load(url, { stepId, databaseConnectionString, clientId },
function () {
$("#confirmButton").removeAttr("style");
});
} else {
//alert('false');
var newUrl = '#Url.Action("Processing", "Client")';
window.location = newUrl;
}
}
});
};
As per this question, I had to remove my contentType property and the values were passed successfully.
<script type="text/javascript">
function runCheck(x, y, z) {
$.ajax({
url: '#Url.Action("ProcessFeedbackHasRows", "Client")',
type: 'POST',
data: { stepId: x, databaseConnectionString: y, clientId: z },
success: function (result) {
if (result.IsValid) {
alert('true');
var url = '#Url.Action("ViewProcessingFeedBackPartial", "Client")';
$("#processingFeedbackPartialDiv").load(url, { stepId, databaseConnectionString, clientId },
function () {
$("#confirmButton").removeAttr("style");
});
} else {
alert('false');
var newUrl = '#Url.Action("Processing", "Client")';
window.location = newUrl;
}
}
});
};
I m working on simple registration i have two forms one is registration another is city, When city is newly added it get added update perfectly but when i use city in registration form eg pune. pune will not get edited or updated, code written in ajax
function UpdateCity(Ids) {
debugger;
var Id = { Id: Ids }
$('#UpdateModel').modal('show');
$.ajax({
type: 'GET',
url: "/City/GetCityDetail",
data: Id,
dataType: "json",
success: function (city) {
$('#EditCityName').val(city.CityName);
$('#EditCityId').val(city.CityId);
}
})
$('#UpdateCityButton').click(function () {
var model = {
CityName: $('#EditCityName').val(),
CityId: $('#EditCityId').val()
}
debugger;
$.ajax({
type: 'POST',
url: "/City/UpdateCity",
data: model,
dataType: "text",
success: function (city) {
$('#UpdateModel').modal('hide');
bootbox.alert("City updated");
window.setTimeout(function () { location.reload() }, 3000)
}
})
})
}
Controller
public bool UpdateCity(City model, long CurrentUserId)
{
try
{
var city = db.Cities.Where(x => x.CityId == model.CityId && x.IsActive == true).FirstOrDefault();
if (city == null) return false;
city.CityName = model.CityName;
city.UpdateBy = CurrentUserId;
city.UpdateOn = DateTime.UtcNow;
db.SaveChanges();
return true;
}
catch (Exception Ex)
{
return false;
}
}
A few stabs in the dark here but, try changing your code to the following (with comments).
Controller:
// !! This is a POST transaction from ajax
[HttpPost]
// !! This should return something to ajax call
public JsonResult UpdateCity(City model, long CurrentUserId)
{
try
{
var city = db.Cities.Where(x => x.CityId == model.CityId && x.IsActive == true).FirstOrDefault();
if (city == null) return false;
city.CityName = model.CityName;
city.UpdateBy = CurrentUserId;
city.UpdateOn = DateTime.UtcNow;
db.SaveChanges();
// !! Change return type to Json
return Json(true);
}
catch (Exception Ex)
{
// !! Change return type to Json
return Json(false);
}
}
Script:
function UpdateCity(Ids) {
//debugger;
var Id = { Id: Ids };
$('#UpdateModel').modal('show');
$.ajax({
type: 'GET',
url: "/City/GetCityDetail",
data: Id,
dataType: "json",
success: function (city) {
$('#EditCityName').val(city.CityName);
$('#EditCityId').val(city.CityId);
},
error: function () {
// !! Change this to something more suitable
alert("Error: /City/GetCityDetail");
}
});
$('#UpdateCityButton').click(function () {
var model = {
CityName: $('#EditCityName').val(),
CityId: $('#EditCityId').val()
};
//debugger;
$.ajax({
type: 'POST',
url: "/City/UpdateCity",
data: model,
// !! Change return type to Json (return type from Server)
dataType: "json",
success: function (city) {
// !! Check result from server
if (city) {
$('#UpdateModel').modal('hide');
bootbox.alert("City updated");
// !! Why reload location?
// window.setTimeout(function () { location.reload(); }, 3000);
} else{
// !! Change this to something more suitable
alert("Server Error: /City/UpdateCity");
}
},
error: function () {
// !! Change this to something more suitable
alert("Error: /City/UpdateCity");
}
});
});
}
This should give you some more clues as to what's going on.
I have web application in ASP.NET MVC C#. I want to call Controller Action method with parameters from javascript but I get always null for parameters.
In .js I have:
$.ajax({
cache: false,
url: this.saveUrl,
type: 'post',
success: this.nextStep,
complete: this.resetLoadWaiting,
error: Checkout.ajaxFailure
});
nextStep: function (response) {
if (response.error) {
if ((typeof response.message) == 'string') {
alert(response.message);
} else {
alert(response.message.join("\n"));
}
return false;
}
if (response.redirect) {
ConfirmOrder.isSuccess = true;
location.href = response.redirect;
return;
}
if (response.success) {
ConfirmOrder.isSuccess = true;
window.location = ConfirmOrder.successUrl;
//window.location.href = #Url.Action("Completed", "Checkout", new { customerComment = "test", customerDate = "2018-12-31" });
//window.location.href = '#Html.GetUrl("Completed", "Checkout", new { customerComment = "test", customerDate = "2018-12-31" })';
}
Checkout.setStepResponse(response);
}
in RouteProvider.cs I have:
routes.MapLocalizedRoute("CheckoutCompleted",
"checkout/completed/{orderId}/{customerComment}/{customerDate}",
new { controller = "Checkout", action = "Completed", orderId = UrlParameter.Optional, customerComment = UrlParameter.Optional, customerDate = UrlParameter.Optional },
new { orderId = #"\d+", customerComment = #"\w+", customerDate = #"\w+" },
new[] { "Nop.Web.Controllers" });
And finaly in Controller I have:
public virtual ActionResult Completed(int? orderId, string customerComment, string customerDate)
{
//some code here
}
I always get parameters value null and I don't know why. I try to call this Action with parameters on several diferent way like I saw on this forum but no success.
Did you add httpPost wrapper to your controller ?
[HttpPost]
public virtual ActionResult Completed(MyClass MyClassObj )
{
//some code here
}
in your Ajax code u didn't mention your Data type And Data try This Ajax
function Save () {
try {
var req = {
DeliveryCode: value,
}
$.ajax({
url: URL,
type: 'POST',
data: req,
dataType: "json",
async: true,
success: function (result) {
resetLoadWaiting()
},
error: function (e) {
}
});
}
catch (e) {
}
}
Mistake was in url string. Correct one is
ConfirmOrder.successUrl = "http://localhost:8079/checkout/completed/?customerComment=eee&customerEstimateShippingDate=2017-11-14"
I found this solution in this answer: Routing with Multiple Parameters using ASP.NET MVC
I dont need to update RouteProvider with new parameters. It is enough to put in in Controller Action method. Other things happen automatically.
I am trying to check if an email address exists in the database. I have an external JavaScript file that I am using to call my jQuery (to keep my view clean). Perhaps it is because I am running with SSL enabled? (I am using https)
Function in external js file:
function checkemail() {
var email = $("#email").val();
$.ajax({
url: "/Account/CheckEmailExists/",
data: JSON.stringify({ p: email }),
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data)
}
});
}
Action in Controller:
public ActionResult CheckEmailExists(string p)
{
bool bEmailExists = false;
using (RBotEntities EF = new RBotEntities())
{
var query = (from U in EF.AspNetUsers
where U.Email == p
select U).FirstOrDefault();
if(query.Email != null)
{
bEmailExists = true;
}
else
{
bEmailExists = false;
}
}
return Json(bEmailExists, JsonRequestBehavior.AllowGet);
}
I seem to be getting an error stating the following:
XML Parsing Error: no root element found Location:
https://localhost:44347/Account/CheckEmailExists/ Line Number 1,
Column 1:
My understanding would be that this ActionResult does not exist. But it does ?
Am I doing something wrong, or is there a reason why an ActionResult can not be called via an external JavaScript file ?
Try this
In Controller
[httppost]
public ActionResult CheckEma.........
In JS
function checkemail() {
var email = $("#email").val();
$.ajax({
url: "/Account/CheckEmailExists/",
data: { p: email },
type: "POST",
success: function (data) {
alert(data)
}
});
}
No need for Json.Stringify and ContentType here
function checkemail() {
var email = $("#email").val();
$.ajax({
url: "/Account/CheckEmailExists",
data: { p: email },
type: "POST",
success: function (data) {
alert(data)
}
});
}
So I found out what was causing the issue...
Above my Action result, I needed to add [AllowAnonymous] data annotation and then it reached my ActionResult! I would prefer to not allow anonymous, but it works and I wanted to share this in case it helps someone else. Below is my code:
ActionResult:
[AllowAnonymous]
public ActionResult CheckEmailExists(string p)
{
bool bEmailExists = false;
using (RBotEntities EF = new RBotEntities())
{
var query = (from U in EF.AspNetUsers
where U.Email == p
select U).FirstOrDefault();
if (query.Email != null)
{
bEmailExists = true;
}
else
{
bEmailExists = false;
}
}
return Json(bEmailExists, JsonRequestBehavior.AllowGet);
}
JavaScript function in JavaScript File:
function checkemail() {
var email = $("#email").val();
var bReturnedValue = false;
$.ajax({
url: "/Account/CheckEmailExists/",
data: { p: email },
async: false,
success: function (data) {
if(data)
{
bReturnedValue = true;
}
else
{
bReturnedValue = false;
}
}
});
return bReturnedValue;
}
And this is how I initiated it(I am doing a popover to specify that the email exists):
$("#createacc_next").click(function () {
var bEmailExists = false;
bEmailExists = checkemail();
if (bEmailExists) {
$("#email").attr("disabled", false).css("border-color", "red");
$('#email').popover({ title: 'Attention', content: 'Email address already exists', placement: 'top', trigger: 'focus' });
Email_Validation_Passed = false;
}
})
I have an $.ajax function on my page to populate a facility dropdownlist based on a service type selection. If I change my service type selection back and forth between two options, randomly the values in the facility dropdownlist will remain the same and not change. Is there a way to prevent this? Am I doing something wrong?
Javascript
function hydrateFacilityDropDownList() {
var hiddenserviceTypeID = document.getElementById('<%=serviceTypeID.ClientID%>');
var clientContractID = document.getElementById('<%=clientContractID.ClientID%>').value;
var serviceDate = document.getElementById('<%=selectedServiceDate.ClientID%>').value;
var tableName = "resultTable";
$.ajax({
type: 'POST',
beforeSend: function () {
},
url: '<%= ResolveUrl("AddEditService.aspx/HydrateFacilityDropDownList") %>',
data: JSON.stringify({ serviceTypeID: TryParseInt(hiddenserviceTypeID.value, 0), clientContractID: TryParseInt(clientContractID, 0), serviceDate: serviceDate, tableName: tableName }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
a(data);
}
,error: function () {
alert('HydrateFacilityDropDownList error');
}
, complete: function () {
}
});
}
function a(data) {
var facilityDropDownList = $get('<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>');
var selectedFacilityID = $get('<%= selectedFacilityID.ClientID%>').value;
var tableName = "resultTable";
if (facilityDropDownList.value != "") {
selectedFacilityID = facilityDropDownList.value;
}
$(facilityDropDownList).empty();
$(facilityDropDownList).prepend($('<option />', { value: "", text: "", selected: "selected" }));
$(data.d).find(tableName).each(function () {
var OptionValue = $(this).find('OptionValue').text();
var OptionText = $(this).find('OptionText').text();
var option = $("<option>" + OptionText + "</option>");
option.attr("value", OptionValue);
$(facilityDropDownList).append(option);
});
if ($(facilityDropDownList)[0].options.length > 1) {
if ($(facilityDropDownList)[0].options[1].text == "In Home") {
$(facilityDropDownList)[0].selectedIndex = 1;
}
}
if (TryParseInt(selectedFacilityID, 0) > 0) {
$(facilityDropDownList)[0].value = selectedFacilityID;
}
facilityDropDownList_OnChange();
}
Code Behind
[WebMethod]
public static string HydrateFacilityDropDownList(int serviceTypeID, int clientContractID, DateTime serviceDate, string tableName)
{
List<PackageAndServiceItemContent> svcItems = ServiceItemContents;
List<Facility> facilities = Facility.GetAllFacilities().ToList();
if (svcItems != null)
{
// Filter results
if (svcItems.Any(si => si.RequireFacilitySelection))
{
facilities = facilities.Where(f => f.FacilityTypeID > 0).ToList();
}
else
{
facilities = facilities.Where(f => f.FacilityTypeID == 0).ToList();
}
if (serviceTypeID == 0)
{
facilities.Clear();
}
}
return ConvertToXMLForDropDownList(tableName, facilities);
}
public static string ConvertToXMLForDropDownList<T>(string tableName, T genList)
{
// Create dummy table
DataTable dt = new DataTable(tableName);
dt.Columns.Add("OptionValue");
dt.Columns.Add("OptionText");
// Hydrate dummy table with filtered results
if (genList is List<Facility>)
{
foreach (Facility facility in genList as List<Facility>)
{
dt.Rows.Add(Convert.ToString(facility.ID), facility.FacilityName);
}
}
if (genList is List<EmployeeIDAndName>)
{
foreach (EmployeeIDAndName employeeIdAndName in genList as List<EmployeeIDAndName>)
{
dt.Rows.Add(Convert.ToString(employeeIdAndName.EmployeeID), employeeIdAndName.EmployeeName);
}
}
// Convert results to string to be parsed in jquery
string result;
using (StringWriter sw = new StringWriter())
{
dt.WriteXml(sw);
result = sw.ToString();
}
return result;
}
$get return XHR object not the return value of the success call and $get function isn't synchronous so you should wait for success and check data returned from the call
these two lines do something different than what you expect
var facilityDropDownList = $get('<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>');
var selectedFacilityID = $get('<%= selectedFacilityID.ClientID%>').value;
change to something similar to this
var facilityDropDownList;
$.ajax({
url: '<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>',
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
facilityDropDownList= data;
}
});