I am unable to retrieve values passed by $.ajax on my c# page.
I am using jqplot and I want to pass two pieces of information. One is stored in a hidden field called 'hidden_plateid' and the second piece of information is from a dropdown box called 'SampleNumberList'
This is the hidden field
<input type="text" name="hidden_plateID" id="hidden_plateID" hidden="hidden" runat="server" />
And this is the drop down box:
<select name="SampleNumberList" class="DropDownBox_editjob" id="SampleNumberList">
<option value="--SELECT--"></option>
<option value="001r">001r</option>
<option value="002r">002r</option>
</select>
I simply then say that everytime, someone selects from the dropdown box, to get and get the information from the db and plot the graph
$('#SampleNumberList').on('change', function (e) {
var ajaxDataRenderer = function (url, plot, options) {
var ret = null;
$.ajax({
data: {
PlateID2: options.PlateID,
SampleID2: options.SampleID,
},
async: false,
url: url,
dataType: "json",
success: function (data) {
alert(data);
ret = data;
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
return ret
};
var jsonurl = "SpectraData.aspx";
var plot2 = $.jqplot('chartdiv', jsonurl, {
title: "AMIRA",
dataRenderer: ajaxDataRenderer,
dataRendererOptions: {
unusedOptionalUrl: jsonurl, PlateID: $('#hidden_plateID').val(), SampleID: $('#SampleNumberList').val()
}
});
});
I use Request.Querystring to try and retrieve the value in the c# file but so far, I get nothing
if (Request.QueryString["PlateID2"] != null)
{
PlateID = Request.QueryString["PlateID2"].ToString();
}
if (Request.QueryString["SampleID2"] != null)
{
SampleID = Request.QueryString["SampleID2"].ToString();
}
You are trying to retrieve values from a query string , yet you are passing the parameters as json.
In order to retrieve them as a query string params, you need to pass them along your url.
$.ajax({
async: false,
url: url + "?PlateID2=" + options.PlateID + "&SampleID2=" + options.SampleID + "",
dataType: "json",
success: function (data) {
alert(data);
ret = data;
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
In reality, the right way to do this is to pass params as a json string and intercept in the code behind.
$.ajax({
url: url/Somemethod,
type: 'POST',
dataType: 'json',
data: "{'PlateID2':'" + options.PlateID + "','SampleID2':'" + options.SampleID + "'}",
success: function (data) {
alert(data);
ret = data;
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
In your codebehind :
[WebMethod]
public static void Somemethod(string PlateID2,string SampleID2)
{
}
Related
I have a switch button on my navbar on my layout view, when I click the button It changes the value and send it to the controller:
<input type="button" id="switchbutton" value="Weekend" style="color:blue" onclick="toggle(this)" >
<script type="text/javascript">
function toggle(button) {
switch (button.value) {
case "Weekend":
button.value = "Week";
break;
case "Week":
button.value = "Weekend";
break;
}
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: '{param: "' + $(this).val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert("Return Value: " + response);
},
failure: function(response) {
alert(response.responseText);
},
error: function(response) {
alert(response.responseText);
}
});
}
</script>
On the controller I receive the value and send it to an If statement that executes a function depending on the value received.
private string SwitchVal;
[HttpPost]
public string AjaxMethod(string param)
{
var d = string.Empty;
switch (param)
{
case "Weekend":
d = "Week";
break;
case "Week":
d = "Weekend";
break;
}
SwitchVal = d;
return d;
}
public JsonResult ModelsUpdate(string SwitchVal)
{
if (SwitchVal == "Weekend")
{
resultminDate = CalculateminDate(minDate, todayDay);
}
else
{
resultminDate = CalculateminDateWeek(minDate, todayDay);
}
The problem is that I do click on the button and I don't see any change, It seems that the value only arrives to the controller the first time. Can anybody help me on this?
It doesn't work like that. You can't hold the values in server side for multiple different requests. Maybe you can use Session to perform it but why don't you post the data ModelsUpdate action instead of AjaxMethod. In your case, I couldn't understand the purpose of AjaxMethod.
public JsonResult ModelsUpdate(string SwitchVal)
{
if (SwitchVal == "Weekend")
{
resultminDate = CalculateminDate(minDate, todayDay);
}
else
{
resultminDate = CalculateminDateWeek(minDate, todayDay);
}
return Json(resultminDate);
}
Ajax call looks like
$.ajax({
type: "POST",
url: "/Home/ModelsUpdate",
data: '{SwitchVal: "' + $(this).val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert("Return Value: " + response);
},
failure: function(response) {
alert(response.responseText);
},
error: function(response) {
alert(response.responseText);
}
});
I'm trying to send a json list populated with the id's from the 'data-seq' attribute only when the 'value' == true.
I have tried out a lot solution but it keeps getting me error messages, the most common are "there is no parameterless constructor for the type string" when using string[] or "string is not supported for deserialization of an array" when using string as code-behind parameter in the WebMethod.
function sentData() {
var json = [];
$('.btn[value="true"]').each(function () {
var obj = {
id: $(this).attr("data-seq")
};
json.push(obj);
});
json = JSON.stringify({ jsonList: json });
console.log(json); // {"jsonList":[{"id":"38468"},{"id":"42443"},{"id":"42444"}]} (the right id's are getting stored)
$.ajax({
type: "POST",
async: true,
url: "Default.aspx/getList",
dataType: "json",
data: json,
contentType: "application/json; charset=utf-8",
error: function (jqXHR, textStatus, errorThrown) {
console.log('bad, ' + errorThrown + ", " + jqXHR.responseText + ", " + textStatus);
},
success: function(json){
//do something with the result
}
});
return false;
}
// Code-Behind
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public static void getList(string jsonList)
{
// string: string is not supported for deserialization of an array
// string[]: there is no parameterless constructor for the type string
}
You are just sending IDs so send them as comma-separated string like this:
function sentData() {
var json = [];
$('.btn[value="true"]').each(function () {
var id = $(this).attr("data-seq")
json.push(id);
});
$.ajax({
type: "POST",
async: true,
url: "Default.aspx/getList",
dataType: "json",
data: '{jsonList: "' + json + '" }',
contentType: "application/json; charset=utf-8",
error: function (jqXHR, textStatus, errorThrown) {
console.log('bad, ' + errorThrown + ", " + jqXHR.responseText + ", " + textStatus);
},
success: function(json){
//do something with the result
}
});
return false;
}
And Code-Behind:
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public static void getList(string jsonList)
{
List<string> ListOfIDs = jsonList.Split(',').ToList();
}
I would like to add Items in jcarousel using c# Webmethod + jquery Ajax
for that i made something like this :
my Html is like :
<div>
<ul id="mycarousel" class="jcarousel-skin-tango" style="float: left">
</ul>
</div>
Jquery code for jcarousel and Ajax Method is like this :
$("#mycarousel").empty();
var element =jQuery('#mycarousel');
$.ajax({
url: "Home.aspx/GetProjectData",
type: "POST",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: "{}",
async: false,
success: function (response) {
if (response.d != null) {
//$.each(response.d, function (i, response) {
$("#mycarousel").html('response.d');
element.jcarousel(
{
pager: true,
visible: 6
});
}
else {
}
},
error: function (xhr) {
}
});
and webmethod is like this :
[WebMethod]
public static List<string> GetProjectData()
{
// here i have 3 list in returnvalue
foreach (var item in returnvalue)
{
var classvalue = item.Soid + "|"
+ item.ProjectTitle + "|"
+ item.Role + "|"
+ item.StartDate + "|"
+ item.EndDate + "|"
+ item.Location.Country + "|"
+ item.Location.State + "|"
+ item.Location.City + "|";
string Template = "<li><img src='../Images/DefaultPhotoMale.png' class='"+ classvalue + "' width='40' height='40' alt='image'/></li>";
list.Add(Template);
}
return list;
}
but problem is , i am not able to images in jcarousel , i only see white box, i am not able to seee images inside, why ?
I'm not sure but wouldn't you need to append the elements sort of like this:
var listItem = $(response.d); //I'm guessing reponse.d is your returned li
element.append(listItem);
I've been trying to get this to work for a few hours now but can't see where I'm going wrong.
I've been checking Firebug for the server response and it retrieves the json data via .asmx web service fine. The only error i have to go off is the one in firebug that's triggered when 2 or more characters are typed in:
TypeError: c.settings[d].call is not a function
jQuery Code Snippet:
$(document).ready(function () {
$("#<%= txtCustomer.ClientID %>").autocomplete({
minLength: 2,
async: true,
source: function(request, response) {
$.ajax({
url: "../Services/AJAXHandler.asmx/GetCustomers",
data: "{'filter':'" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function(item) {
return {
label: item.customerName
};
}));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
var errorMessage = "Ajax error: " + this.url + " : " + textStatus + " : " + errorThrown + " : " + XMLHttpRequest.statusText + " : " + XMLHttpRequest.status;
if (XMLHttpRequest.status != "0" || errorThrown != "abort")
{
alert(errorMessage);
}
}
});
}
});
If anybody could point me in the right direction that would be brilliant.
I am using ASPNET MVC 2.0. I'm trying to pass a value from View to Controller function using jquery function .ajax. My jquery function is:
$(document).ready(function() {
$("#Search").click(function(event) {
var searchString = $("#TraderSearch").val();
$.ajax({
type: 'POST',
url: '/Build/SearchTrader',
data: "{strData : '" + searchString + "' }",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(ResultList) {
var contents = "";
var count = 0;
$(ResultList).each(function() {
contents = contents + '<tr><td>' + ResultList[count].Name + '</td><td>' + ResultList[count].Value +
'</td><td><a class="edit"><img src="../../html/images/Edit.gif" width="14" height="14" alt="edit" /></a></td></tr>';
count = count + 1;
});
$("#SerachResultList").append(contents);
alert("{strData : '" + searchString + "' }");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + textStatus + "\n" + errorThrown);
}
});
});
});
And my Controller function is as follows:
public ActionResult SearchTrader(string strData)
{
//Function to search DB based on the string passed
return Json(lstDictObject);
}
My problem is that, I am not able to get the value in my controller. I'm getting strData as 'null'. I think there is somme mistake in the way i'm trying to pass the value? Can anyone correct me?
Thanks in Advance,
Vipin Menon
try this:
data: "strData = " + searchstring
I believe the following should work:
data: { strData: searchstring }
Quotes caused the same issue in the script I just tested.
You also need to check the spelling on your "#SerachResultList" if this is your actual code.