I am calling a Web Method using Json and get HTML as a result.
I'm trying to set the value of a hidden field with this HTML and then access this hidden field from
server side but the hidden field value is always empty.
please help.
thanks
$.ajax({
type: "POST",
url: "ws/srv.asmx/GetReportResult",
data: JSON.stringify(prm),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, status) {
var result = JSON.parse(data.d);
$("myHiddenField").val = result;
},
error: function (request, status, error) {
alert(request.statusText);
}
});
Try changing this line
$("myHiddenField").val = result;
To become
$("myHiddenField").val(result);
Jquery val is a function, so the parenthesis will fix the assignment.
are you have a hidden field control on server side? Than maybe your hidden field id is not myHiddenField when rendered to the page. Check your hidden field on browser and make sure its id is myHiddenField.
if it something like ct100_ct1242_myhiddenField than you can change
$("#myHiddenField").val = result;
with
$("[id$='myHiddenField']").val = result;
and if there is no codes changing the hidden field value on page load , page init etc you should see the result.
Related
I am working on asp.net application. Where for a page I have to clear the value of the controls(like textbox and dropdownlist,etc), also i have to remove the value of a ViewState. Initailly i was doing it from codebehind, so o problem was there. But now the problem arise when i tried reset the value of controls using client side , say
document.getElementById('<%= txtTextBox.ClientID %>').value ='';
but the problem i am facing is that i cannot set the viewstate value from clientside.
my i have to clear to viewstate one is a simple variable say ViewState["NameOfUser"],and another one is converting a datatable into viewstate say,
ViewState["dataTable"] = dt;
Thanks and regards
You simply can not assign value in client side.
Either you have to pass it through hidden field while submitting form or
Call ajax from javascript and access the ViewState server side.
I found this way via ajax request:
Credits: https://forums.asp.net/t/1991868.aspx?Set+value+of+Viewstate+from+Javascript+or+Jquery
ViewState["dataTable"] = dt;
Javascript:
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(function () {
$("#Button1").click(function () {
//clear datatable
$.ajax({
type: "POST",
url: "WebForm1.aspx/ClearDataTable",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('cleared');
}
});
//clear other values.....
//............
});
})
</script>
On codebehind:
[WebMethod]
public static void ClearDataTable()
{
HttpContext.Current.Session["datatable"] = null;
}
Hope that it helps!
I was looking on internet for over 2 hrs now, trying to find simple example of how to fill jQuery Variable from serverside code on load of asp.net page.
What i have so far:
I have a button which call this jquery code:
function GetListOfQuestions() {
$.ajax({
type: "POST",
url: 'UserProfile.aspx/getQuestions',
contentType: "application/json; charset=utf-8",
dataType: "json",
error: OnAjaxError,
success: AjaxSucceeded
});
//$.getJSON('UserProfile.aspx/getQuestions', {}, function (data) {
// alert(data);
//});
}
function AjaxSucceeded(result) {
alert(result);
}
GetListOfQuestions calls serverside :
[WebMethod]
public static List<Question> getQuestions(){
var userGuid = (Guid)System.Web.Security.Membership.GetUser().ProviderUserKey;
IEnumerable<Question> list = Question.getQuestionsForUser(userGuid).Select(x => new Question
{
Uid = x.Uid,
Content = x.Content
});
return list.ToList();
}
result return an object if I alert it, so it must contain some kind of data, but I can't find any example of how I can retrieve data again on client side.
I'm not sure if what I am doing right now is right at all (I'm new to jQuery). So how can I retrieve data from result variable again?
There could be better ways but this is one way I know of:
[WebMethod]
public static string getQuestions(){
var userGuid = (Guid)System.Web.Security.Membership.GetUser().ProviderUserKey;
IEnumerable<Question> list = Question.getQuestionsForUser(userGuid).Select(x => new Question
{
Uid = x.Uid,
Content = x.Content
});
return new JavaScriptSerializer().Serialize(list.ToList())
}
In your jQuery method, you can
result = $.parseJSON(data) ;
Do a console.log(result) to see how to iterate through result, should be just a for loop.
Put a hidden field on your page an set the variable value there, later read the hidden value from js.
Another option is to use ScriptManager.RegisterStart UpScript to write your variable directly as js to the page.
I'm trying to execute a server side method using this technique:
Javascript Ajax function
function storeLocal(brand, type) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{brand:'" + brand + "'}",
url: "Jquery Site.Master/storeLocal",
datatype: "json",
success: OnSuccess(brand),
});
}
function OnSuccess(brand) {
alert(brand);
}
C# method:
[WebMethod]
public static object storeLocal(string brand)
{
HttpContext.Current.Session.Add("Brand", brand);
}
line of code to execute is:
<li>
<a class="strong" onclick="storeLocal('petzl','harness')" href="About.aspx">Harnesses</a>
</li>
but its not executing correctly is there any particular error in my code?
reasone i am using this method is because i want to have a dynamic menu for a small project and wish to store in session what specific "li" did a user select in session so that i can load the content in the redirected page.
Thanks alot
Adrian
There is no return in your method that is might be the poblem, you method should be like as below
[WebMethod]
public static object storeLocal(string brand)
{
HttpContext.Current.Session.Add("Brand", brand);
return "value" +brand;
}
There are a couple of errors I can see with your ajax request:
The url parameter value isn't a proper URL.
Your not assigning your OnSuccess method correctly.
Try changing it to:
function storeLocal(brand, type) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{brand:'" + brand + "'}",
url: "ProperSiteUrl/storeLocal",
datatype: "json",
success: OnSuccess,
});
}
And you aren't returning anything from your storeLocal web method. Try changing it to:
[WebMethod]
public static object storeLocal(string brand)
{
HttpContext.Current.Session.Add("Brand", brand);
return ...;
}
Also, your sending JSON to the server, however, for a single parameter it you might find it easier just to send it as key/value pair e.g.
...
data: "brand=" + brand
...
i am not sure if your code is right! you have given both href and onclick and the page might navigate to about.aspx even before the onclick ajax event is completed.
try to remove the href or put the onclick event inside a href='javascript:storelocal()' and return the value from webmethod.
keep a breakpoint in the webmethod and see if the content is getting passed to the webmethod or not.
The url and success doens't look good.
1 - Within the ajax call you don't pass a argument to the success function. it will be returned something by the webmethod specified in c#.
you specify data in the data propriety, and that is used as the arguments passed to the webmethod.
2 - You can't call the webmethod using you master page, it has to be specified in the page that you are working. the aspx file not the master.
The page inherits from master, but it's not the master. Is a page with specification of the master page file.
Try this to identify errors, this for seeing what is returned
error: function (error) {
alert(JSON.stringify(error));
}
Inside my controller there is JsonResult action which returns me a list of House object.
I want onclick using ajax to retrieve these data and to display json data inside my view.
Inside firebug I'm able to see proper Response and Json result but I dont know how to display inside my view.
function GetTabData(xdata) {
$.ajax({
url: ('/Home/GetTabData'),
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ id: xdata }),
success: function (result) {
// tried with these but it doesnt work
// result = jQuery.parseJSON(result);
// alert(result.Title);
},
error: function () { alert("error"); }
});
}
public JsonResult GetTabData()
{
...
var temp = getMyData...
return Json(temp, JsonRequestBehavior.AllowGet);
}
// View page
<div id="showContent">
// Json data should appear here
</div>
Inside firebug JSON tab when success:function(result) is empty
I have following data:
Id 149
PropertyType "Apartment"
StreetNumber "202B"
CityName "Sidney"
Title "My test data"
success: function (json) {
var data = null;
$.each(json.items,function(item,i){
data = '<div>'+item.Id+ ' ' + item.CityName +'</div>';
$("#showContent").append(data);
});
}
First of all, you can specify the dataType attribute in your ajax call to 'json' and then don't have to decode the json response again -
dataType: 'json'
Then, you don't need to use parseJSON. Simply use result.Title etc.
success: function (result) {
alert(result.Title);
var showContent = $('#showContent');
showContent.html(result.Id+','+result.Title);
},
EDIT: As Mukesh said, you can have the ajax function return json without using any extra decoding.
The ajax call result is already an object. You can do whatever you want with it it inside the success function.
For example you could create a table of the information dynamically inside the function, or send the data to another function by calling the function inside that success function. Once you leave the success function, the data is not usable anymore.
Access the data object like any object (data.someProperty).
I'm currently working on a ASP.NET Webforms site and I've run in to a small problem. Been searching around for 2 hours now and I got a deadline, so hoping someone here can assist.
On my .cs file I have the following Webmethod
[WebMethod]
public static string IsJobEditable(int jobid)
{
try
{
string isEditable = "false";
JobsBLL jbl = new JobsBLL();
int jobStatusId = jbl.GetJobStatusId(jobid);
if(jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Waiting) || jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Edit))
{
isEditable = "true";
}
return isEditable;
}
catch (Exception ex)
{
throw ex;
}
}
This function in this case will ALWAYS return TRUE as a string.
On Aspx page I have the following
$(function () {
$.ajax({
type: "POST",
url: "Coordination.aspx/IsJobEditable",
data: "{jobid:" + jobid + "}",
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function (result) {
alert(result);
// This is written out in the alert {"d":"true"}
// I want this in a variable as a string
// so I can do a check on it before I do some other actions
// The format is not a String so i cannot split on it to
// retrieve the "true" part.
},
error: function (err, result) { alert(err); }
});
});
As you can see in the comments the value I get back in the Callback method is in to me a weird format. The type is unknown and I need this value to be able to proceed with my entire method surrounding the small portion of the Javascript.
So can anyone point me into the direction where I can access the result variable / data as a var or anything else that will let me put it into a var (as a string).
Use result.d to get your string.
See this site for an explanation of the .d issue when calling .ajax from ASP.NET: http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/
try alert(result.d);
You can easily retrieve the "true" part like this:
alert(result.d);
The reason the object is wrapped in the "d" json object is security. You can read about it for example here.
According to two articles I found, I think you want to specify "DataType" as json not as text (since you're expecting a content-type of json to be returned). That may be your issue, though i don't have a sample project in front of me to test on. Your result is also probably result.d as outlined in those same articles.
This solved it:
$(function () {
$.ajax({
type: "POST",
url: "Coordination.aspx/IsJobEditable",
data: "{jobid:" + jobid + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result.d);
//I finally got the data string i wanted
var resultAsString = result.d;
},
error: function (err, result) { alert(err); }
});
});
So 2 things were done to solve this. I had to change the dataType to "json" and I used the result.d to retrieve my data.
What threw me off was the lack of intellisens on the result object. But the .d (data) property however solved it.
Thanks you to all who contributed to this answer.