How to pass parameters from Ajax function to controller action? - javascript

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;
}
}
});
};

Related

ASP.NET MVC call Controller Action with parameter from javascript function

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.

AJAX call in external JavaScript file not reaching ActionResult in controller

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;
}
})

getting anonymous function error in ajax

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...
}
});

Controller not receiver parameter passed by ajax POST in .Net MVC

I want to make an ajax shopping cart, the GetCarts and AddCart all working, but the RemoveRow not
receiver the parameter "strms". When alert(strms) in removeRow(strms) js function, it show right value
of the book id (equal 8). But in the CartController/RemoveRow debug, the strms value is NULL.
I think it's can be a problem with the routing, but I think my route configs are right!
Please help me.
The view is _Layout.cshtml, which contain js code
The controller is CartController
My RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Sach", action = "Detail", id = "7" }
);
routes.MapRoute(
"Cart",
"{controller}/{category}/{ms}/{sl}",
new { controller = "Cart", action = "AddCart", ms = UrlParameter.Optional, sl = UrlParameter.Optional }
);
routes.MapRoute(
"CartRemoveRow",
"{controller}/{action}/{ms}",
new { controller = "Cart", action = "RemoveRow", ms = UrlParameter.Optional });
}
}
CartController.cs
public class CartController : Controller
{
List<CartItem> listCart;
[HttpPost]
public ActionResult GetCarts()
{
listCart = Cart.getCart(Session);
return PartialView("Cart", listCart);
}
public void AddCart(string ms, string sl) {
int masach = int.Parse(ms);
int soluong = int.Parse(sl);
Cart.AddCart(masach, soluong, Session);
//return PartialView("Default");
}
public void RemoveRow(string strms)
{
int ms1 = int.Parse(strms);
var sach = new Sach() { MaSach = ms1 };
Cart.removeCart(sach, true);
}
}
Ajax js code
<script type="text/javascript">
function showCart() {
// alert("1");
//Load content from CartController
$(function () {
//alert("2");
$.ajax({
type: "POST",
url: '#Url.Action("GetCarts", "Cart")',
success: function (data) {
var result = data;
$('#myCart').html(result);
//alert($('#myCart').html());
}
});
});
$("#myCart").modal('show');
}
function addCart(ms, sl) {
var masach = [];
masach.push(ms);
masach.push(sl);
// alert(masach);
$(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("AddCart", "Cart")/'+ms+'/'+ $("#soluong").val(),
success: function (data) {
showCart();
}
});
return false;
});
}
function removeRow(strms){
$(function () {
// alert(strms);
$.ajax({
type: 'POST',
url: '#Url.Action("RemoveRow", "Cart")/' + strms,
success: function (data) {
showCart();
}
});
});
}
</script>
try passing the parameter in the data property, I have multiple examples but not at home right now.
function removeRow(this_strms){
$(function () {
// alert(strms);
$.ajax({
type: 'POST',
url: '#Url.Action("RemoveRow", "Cart")',
data: { strms: this_strms},
success: function (data) {
showCart();
}
});
});
}
I normally pass C# objects/classes as parameters like this
public void RemoveRow(CartObject strms)
{
int ms1 = strms.ms1;
var sach = new Sach() { MaSach = ms1 };
Cart.removeCart(sach, true);
}
in JS i do something like this
var thisCartObject= {
ms1: 1,
otherproperty: 0.4,
otherproperty2: "Description"
};
function removeRow(thisCartObject){
$(function () {
// alert(strms);
$.ajax({
type: 'POST',
url: '#Url.Action("RemoveRow", "Cart")',
data: JSON.stringify({ strms: thisCartObject}),
contentType: 'application/json',
dataType: 'json',
success: function (data) {
showCart();
}
});
});
}
If you are going to try this, try without! your custom route defined in the RegisterRoutes class first.
Rename the javascript variable: "strms" to "ms" and then send it, because in your route "CartRemoveRow" you will receive a variable declared with the name "ms" not "strms".
And of course, in your controller, rename the parameter in the method "RemoveRow" to "ms".
Or more short, change your route to accept "strms":
routes.MapRoute(
"CartRemoveRow",
"{controller}/{action}/{strms}",
new { controller = "Cart", action = "RemoveRow", strms = UrlParameter.Optional });
}

Does jQuery.ajax() not always work? Is it prone to miss-fire?

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;
}
});

Categories

Resources