Data passing error from javascript to controller - javascript

I'm working on ASP.NET MVC project , I want to get location dropdown selected value and according to that i need to load values to City dropdown , i implemented following code and location dropdown onselect event call the javascript function and javascript function call the controller method but when executing controller method locationId is null ,and i debug javascript and locationID is there till the this line data: JSON.stringify({ locationId: +locationId }), after that javascript returns error.but controller method get hit but locationId null
code for dropddowns
<div class="row">
<div class="col-sm-4">
#Localizer["Locations"]
<select id="locationDropDown" class="selectpicker form-control" asp-for="selectedLocation" onchange="getCityList()">
<option value="0"><None></option>
#foreach (var item in Model.LocationList)
{
<option value="#item.Id">#item.Name</option>
}
</select>
</div>
</div>
<div class="row">
<div class="col-sm-4">
#Localizer["KioskGroup"]
<select id="cityDropDown" class="selectpicker form-control">
<option>---Select City---</option>
</select>
</div>
</div>
Javascript code
function getCityList()
{
debugger;
var locationId = $("#locationDropDown").val();
console.log(locationId)
$.ajax({
url: '/Kiosk/GetZoneListBYlocationID',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({ locationId: +locationId }),
success: function (result) {
$("#cityDropDown").html("");
$("#cityDropDown").append
($('<option></option>').val(null).html("---Select City---"));
$.each($.parseJSON(result), function (i, zone)
{ $("#cityDropDown").append($('<option></option>').val(zone.Id).html(zone.Name)) })
},
error: function(){alert("Whooaaa! Something went wrong..")},
});
controller method
public ActionResult GetZoneListBYlocationID(string locationID)
{
List<Zone> lstZone = new List<Zone>();
long locationId = long.Parse(locationID);
var zones = _zoneRepository.GetZonesByLocationId(locationId);
return Json(JsonConvert.SerializeObject(zones));
}

Your current code is sending the json string {"locationId":101} in the request body because you specified the contentType as application/json. This is useful when you want to send an object with multiple properties and your action method parameter is a DTO/POCO class type. Model binder will be reading from the request body and map it to the parameter.
In your case, all you are sending is a single value. So do not send the JSON string. simply create a js object and use that as the data attribute value. Also remove the contentType: application/json as we are not sending a complex js object as json string.
Also application/json is not a valid option for the dataType property. You may use json. But jQuery is smart enough to guess the value needed here from the response headers coming back from server. So you may remove it.
function getCityList() {
var locationId = $("#locationDropDown").val();
$.ajax({
url: '/Kiosk/GetZoneListBYlocationID',
type: 'POST',
data: { locationID: locationId },
success: function (result) {
console.log(result);
// populate dropdown
},
error: function () { alert("Whooaaa! Something went wrong..") },
});
}
Now this data will be send in Form Data as locationID=101 with Content-Type header value as application/x-www-form-urlencoded and will be properly mapped to your action method parameter.
You should use the correct types. In your action method, you are using string as your parameter and later trying to convert it to long. Why not use long as the parameter type ? Also if zones variable is a list of Zone object, you can pass that directly to the Json method. No need to create a string version in between.
public ActionResult GetZoneListBYlocationID(long locationId)
{
var zones = _zoneRepository.GetZonesByLocationId(locationId);
return Json(zones);
}

Why you are stringify the data.Below one should work without stringify
data: { locationId: +locationId },

I was facing the same problem. and after that, I have tried below solution.
Hope it will help you.
ajax call is as follows:
$.ajax({
type: 'POST',
url: "/Account/GetCities",
dataType: 'json',
data: { id: $("#StateID").val() },
success: function (states) {
$.each(states, function (i, state) {
$("#CityID").append('<option value="' + state.Value + '">' + state.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve cities.' + ex);
}
});
The controller code is as follows:
public List<CityModel> GetCities(int id)
{
//your code
}
You can do in your application like this:
function getCityList()
{
var locationId = $("#locationDropDown").val();
console.log(locationId)
$.ajax({
url: '/Kiosk/GetZoneListBYlocationID',
type: 'POST',
dataType: 'json',
data: { locationId: locationId },
success: function (result) {
$("#cityDropDown").html("");
$("#cityDropDown").append
($('<option></option>').val(null).html("---Select City---"));
$.each($.parseJSON(result), function (i, zone)
{ $("#cityDropDown").append($('<option></option>').val(zone.Id).html(zone.Name)) })
},
error: function(){alert("Whooaaa! Something went wrong..")},
});
}
And your controller will be same as you have done.

Related

Why is my ajax not passing in my parameter (always empty) via POST in Razor Page application?

I need this ajax call to run my onpost handler PassPart. It successfully calls it, but my parameter "searchedpart" is always empty. I've also tried passing the parameter directly in my url, like: "?handler=passPart" + "&searchedpart=" + searchedpart , but it's still empty. Lastly, I've tried using "Request.Form[SearchedPart]" in my method to pull the value in, also empty. I've tested that this element is not empty by adding an alert message to my js to confirm, and I see the value being found.
ps. I'm using an EmptyResult because I don't need anything posted back. I simply need it to run through my handler using the parameter.
<form method="post">
<input class="form-control" name="searchedpart" asp-for="PostData.SearchedPart" value="#Model.PostData.SearchedPart" id="searchedpart" />
<button type="submit" id="searchpartbtn" class="btn btn-success btn-sm">Find</button>
</form>
document.getElementById('searchpartbtn').addEventListener('click', PassPart);
var searchedpart = document.getElementById('searchedpart').value;
function PassPart() {
$.ajax({
type: "POST",
url: "?handler=passPart",
dataType: "json",
data: JSON.stringify({ searchedpart: searchedpart }),
beforeSend: function (xhr) {
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
}
});
}
public ActionResult OnPostPassPart(string searchedpart = "")
{
if (searchedpart != "") {
// Do Things
}
return new EmptyResult();
}
Because searchedpart is already a string type, there is no need to JSON.stringify.And you should write your var searchedpart = document.getElementById('searchedpart').value;code inside your function.
Just change your code as below:
document.getElementById('searchpartbtn').addEventListener('click', PassPart);
function PassPart() {
var searchedpart = document.getElementById('searchedpart').value;
$.ajax({
type: "POST",
url: "?handler=PassPart",
dataType: "json",
data: { "searchedpart": searchedpart },
beforeSend: function (xhr) {
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
}
});
}
In your background:
public ActionResult OnPostPassPart(string searchedpart)
{
//...
}
Result:
I ended up using the following in my method to get this working:
string part = Request.Form["SearchedPart"];
remove dataType: "json"
Add header token

Parameter contains a NULL entry when it isn't during AJAX call

I need to implement functionality to upload files and save them relevant to the orderItemID (which I can get). The problem isn't getting the ID or using the ID to then save the files to the DB. The problem is passing this ID (which I can log out and see is there) into the controller to then be used, the parameter continues to come back NULL when it isn't.
I initially tried passing the orderItemID as a second parameter when uploading the document but that resulted in both the HttpPostedFileBase and the int of orderItemID coming back as NULL as soon as I entered the method.
I've tried passing the orderItemID through the ViewBag. feature but again it comes back as NULL
I'm now trying to make a second separate AJAX call which simply passes in an int (orderItemID) and then in the controller I can try other things but for now I'd just like to see the parameter not returning as NULL when I hit the breakpoint in the orderController.
View:
$('#confirmUploadDiagrambtn').on("click", function () {
var currentID = document.getElementsByName("orderitemid")[0].value;
var form = $("#file")[0].files[0];
var datastring = new FormData();
datastring.append('file', form);
//Order Item ID is logged out as the expected 12121
console.log("OrderID: " + currentID);
//Errors out saying parameter is NULL
setOrderItemID(currentID);
uploadDocument(datastring);
})
function setOrderItemID(cOrderItemID) {
$.ajax({
type: "POST",
url: '/Order/SetCurrentOrderItemID',
data: cOrderItemID,
contentType: false,
processData: false,
success: function (response) {
console.log('Item Success');
console.log(response);
},
error: function (status) {
console.log('Item Error');
console.log(status);
}
})
}
Controller:
[HttpPost]
public void SetCurrentOrderItemID(int orderItemID)
{
//I can try whatever later, just need the param to not be NULL
ViewBag.cOrderItemID = orderItemID;
}
Expected: orderItemID will equal 12121
Actual: NULL
Error: The parameters dictionary contains a null entry for parameter 'orderItemID' of non-nullable type 'System.Int32' for method 'Void SetCurrentOrderItemID(Int32)'
the "data" property in the AJAX parameters should look like:
data: "cOrderItemID=" + cOrderItemID
EDIT:
remove this line:
contentType: false,
use this format:
data : {OrderItemID : cOrderItemID}
By default int parameters are assumed to come from the query string, you could either change the url to:
function setOrderItemID(cOrderItemID) {
$.ajax({
type: "POST",
url: '/Order/SetCurrentOrderItemID?orderItemID=' + cOrderItemID,
contentType: false,
processData: false,
success: function (response) {
console.log('Item Success');
console.log(response);
},
error: function (status) {
console.log('Item Error');
console.log(status);
}
})
}
Or else you could mark the parameter with the [FromBody] attribute:
[HttpPost]
public void SetCurrentOrderItemID([FromBody] int orderItemID)
{
//I can try whatever later, just need the param to not be NULL
ViewBag.cOrderItemID = orderItemID;
}
and then update your data parameter to:
data: JSON.stringify({orderItemId: cOrderItemID}),

Calling [HTTPPost] from Javascript ASP.NET

I am using a method in my controller which imports data from an API. This method I am wanted to be called from two locations. First the view (currently working) and secondly a javascript function.
Start of controller method:
[ActionName("ImportRosters")]
[HttpPost]
public ActionResult PerformImportRosterData(int id, int? actualLength, int? rosterLength)
{
var authenticator = Authenticator(id);
var rosters = authenticator.Api().RosterData().ToDictionary(x => x.Id);
var databaseRosterDatas = SiteDatabase.DeputyRosterData.Where(x => x.SiteID == id)
.ToDictionary(x => x.Id);
Javascript Function:
$("#btnDeputyRunNowUpdate").click(function() {
$("#btnRunDeputyNow").modal("hide");
ActualLength = $("#actualRunLength").val();
RosterLength = $("#rosterRunLength").val();
$.ajax({
type: "POST",
url: "/deputy/PerformImportRosterData",
data: { SiteIDRoster, ActualLength, RosterLength }
});
SiteIDRoster = null;
location.reload();
$("#btnRunDeputyNow").modal("hide");
toast.show("Import Successful", 3000);
});
All values are being set but i am getting a 404 error on the url line
POST https://example.org/deputy/PerformImportRosterData 404 ()
I need a way to be able to call this c# method from both html and JS
This can be done if you will modify the URL in your AJAX. It should look something like
url: '<%= Url.Action("YourActionName", "YourControllerName") %>'
or
url: #Url.Action("YourActionName", "YourControllerName")
one more thing, I don't see if you do anything with the result of the call. your script does not have success part
success: function(data) {//do something with the return}
and would be very helpful to have error handler in your call.
full example on how AJAX should look like:
$.ajax({
url: "target.aspx",
type: "GET",
dataType: "html",
success: function (data, status, jqXHR) {
$("#container").html(data);
alert("Local success callback.");
},
error: function (jqXHR, status, err) {
alert("Local error callback.");
},
complete: function (jqXHR, status) {
alert("Local completion callback.");
}
})
For a good tutorial on AJAX read this document
Change after Comment:
my current code is below:
$("#btnDeputyRunNowUpdate").click(function() {
$("#btnRunDeputyNow").modal("hide");
ActualLength = $("#actualRunLength").val();
RosterLength = $("#rosterRunLength").val();
$.ajax({
type: "POST",
url: '<%= Url.Action("PerformImportRosterData", "DeputyController") %>',
data: { SiteIDRoster, ActualLength, RosterLength },
success: function(data) {
console.log(data);
console.log("TESTHERE");
}
});
}
UPDATE:
Noticed one more thing. Your parameters in the controller and AJAX do not match. Please try to replace your a few lines in your AJAX call with:
url: "/deputy/PerformImportRosterData",
data: { id: yourIDValue, actualLength: youractualLengthValue,
rosterLength :yourrosterLengthValue }
remember to set all variable values in javascript , if they have no values set them = to null.
Can you try copy paste code below
$.ajax({
type: "POST",
url: "/deputy/PerformImportRosterData",
data: { SiteIDRoster:999, ActualLength:1, RosterLength:2 }
});
And let me know if it wall cause any errors.
After attempting to solve for a few days, I created a workaround by creating two methods for importing the data. one for the httpPost and the second for import calling from javascript.
Not a great solution but it works. Thanks for your help Yuri

ajax request not sending any data ASP.NET MVC project with jQuery

I'm fairly new to asp.net MVC but am baffled as to why my request isn't working.
I'm trying to send an ajax request with jquery as per:
jQuery(function ($) {
var total = 0,
share = $('div.share'),
googlePlusUrl = "https://plusone.google.com/_/+1/fastbutton?url=http://bookboon.com" + $(location).attr('pathname');
setTimeout(function() {
$.ajax({
type: 'GET',
data: "smelly",
traditional: true,
url: share.data('proxy'),
success: function(junk) {
//var $junk = junk.match(regex);
console.log(junk);
},
error: function (xhr, errorText) {
console.log('Error ' + xhr.responseType);
},
});
}, 4000);
And set a line in my RouteConfig as:
routes.MapRoute(null, "services/{site}/proxy", new { controller = "Recommendations", action = "Proxy" });
The markup has a data-attribute value as:
<div class="share" data-proxy="#Url.Action("Proxy", "Recommendations")">
And my Proxy action method starts with:
public ActionResult Proxy(string junk)
The problem is that the junk parameter is always null. I can see in the debug output that the route seems to correctly redirect to this method when the page loads (as per jQuery's document ready function), but I cannot seem to send any data.
I tried sending simple data ("smelly") but I don't receive that neither.
Any suggestions appreciated!
The model binder will be looking for a parameter in the request called junk, however you're sending only a plain string. Try this:
$.ajax({
type: 'GET',
data: { junk: "smelly" }, // <- note the object here
traditional: true,
url: share.data('proxy'),
success: function(junk) {
//var $junk = junk.match(regex);
console.log(junk);
},
error: function (xhr, errorText) {
console.log('Error ' + xhr.responseType);
},
});

Posting JSON string to ASP.NET MVC 3 action results in null parameter

I am posting a JSON string to asp.net MVC as follows.
AJAX call
$.ajax({
type: "POST",
url: "#(storeLocation)IDR/OpcInsertCustomerProfile/",
data: JSON.stringify(currSelection),
contentType: "application/json",
success: function(data) {
alert('success : ' + JSON.stringify(data));
},
error: function(data) {
alert('Error : ' + JSON.stringify(data));
}
}
);
In the controller:
[HttpPost]
[ActionName("OpcInsertCustomerProfile")]
public JsonResult OpcInsertCustomerProfile(string currSelectionData)
{
try
{
JavaScriptSerializer ser = new JavaScriptSerializer();
var res = ser.Serialize(currSelectionData);
return Json(currSelectionData, JsonRequestBehavior.AllowGet);
}
catch (Exception exc)
{
return Json(new { error = 1, message = exc.Message });
}
}
Debugger indicates the action gets called successfully, however the incoming string parameter being received is always null. Firebug 'post' shows outgoing parameter is proper json object. I am expecting to see the JSON string as incoming parameter. Please note that I don't want to de-serialise it into proper object. All I want to do is store the string in JSON format 'as-it-is' in a database. Later on it needs be retrieved ans passed to Javascript as it is.
Try this :
$.ajax({
type: "POST",
url: "#(storeLocation)IDR/OpcInsertCustomerProfile/",
data: { "currSelectionData" : "'" + JSON.stringify(currSelection) + "'" },
contentType: "application/json",
success: function(data) {
alert('success : ' + JSON.stringify(data));
},
error: function(data) {
alert('Error : ' + JSON.stringify(data));
}
}
);
One way is to allow the action to receive the parameter as POST data instead of JSON "Stringified" data. To do that, post the data without JSON.Stringify. Hopefully this is what you need.
If not you might want to try creating an object just to receive this simple data.
Look at your action method: is it correct that method accepts string with serialized JSON, than serialized that string as JSON again and then dismiss the result and serializes and returns the same string again?
If you send request with application/json type ASP.NET MVC tries to deserialize received string and bind it to action parameters: in your case it tries to find property currSelectionData inside your JSON object. Is that property exists? Maybe you expect whole string is received as currSelectionData parameter? Then you need to use FormCollection or Request.Form instead because default model binder does not support this.
Actually i fill my state dropdown in selection of country with json i do like this
in my controller i have action it's return my data in json format like this it's below
public JsonResult State(int countryId)
{
var stateList = CityRepository.GetList(countryId);
return Json(stateList, JsonRequestBehavior.AllowGet);
}
in my view
<script type="text/javascript">
function cascadingdropdown() {
$("#stateID").empty();
$("#stateID").append("<option value='0'>--Select State--</option>");
var countryID = $('#countryID').val();
$.ajax({
url: "/City/State",
dataType: 'json',
data: { countryId: countryID },
success: function (data) {
$("#stateID").empty();
$("#stateID").append("<option value='0'>--Select State--</option>");
$.each(data, function (index, optiondata) {
alert(optiondata.StateName);
$("#stateID").append("<option value='" + optiondata.ID + "'>" + optiondata.StateName + "</option>");
});
},
error: function () {
alert('Faild To Retrieve states.');
}
});
}
</script>
i think this will help you...
When sending json through Ajax, I think this is the right approach for the data property in Ajax:
data: "{'parameterNameInAction':'" + JSON.stringify(jsonData) + "'}"

Categories

Resources