I am using a web method for ajax call, I want to change the text of my asp.net label control after ajax call.
I am changing its text on success of the ajax call,but after post back I am not getting updated value, as its changing on client side.
I want to change text so that it will reflect on post back as well.
How can I change the text of label in WebMethod?
Below is my code
[System.Web.Services.WebMethod()]
public static string RemoveVal()
{
//Do some work
//Return updated Value
//I want to change text here
}
jQuery.ajax({
type: "POST",
url: 'MyPage.aspx/RemoveVal',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var emaillbl = GetClientID("lblEmail").attr("id");
$("#" + emaillbl).html(data);
}
});
<asp:Label ID="lblEmail" runat="server" CssClass="labelclass"></asp:Label>
function GetClientID(id, context) {
var el = $("#" + id, context);
if (el.length < 1)
el = $("[id$=_" + id + "]", context);
return el;
}
AJAX call will update control text in client side only. If you want to change label's text after post back , bind the changed value again to the control while page posts back. Like you can call function which binds changed value to label in postback event OR in page load wherever seems fit.
Related
I make a webmethod call and get an answer from the server if the current user can/can't print a document.
If the user can print, I want to display a print button. Otherwise not.
Is there a way to add a print button to an existing "div" from a web method?
You should try something like this(sorry, not tested)
$.ajax({
type: "POST",
url: "/yourPage.aspx/YourWebMethod",
data: "{yourParameterName:'" + yourparamvalue + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
var element = document.createElement("input");
element.setAttribute("type", "button");
element.setAttribute("value", "invert");
element.setAttribute("name", "button3");
element.setAttribute("onclick", "foo()");
var targetElement = document.getElemanById('yourdivid');
targetElement.appendChild(element);
},
error: function () { alert('/yourPage.aspx/YourWebMethod'); }
});
You dont need to add from web method, simply add button where ever you want to show, make sure it is hidden by default. check the value return from page method and show/hide button based on value.
PageMethods.CheckPermission(function (flag) {
if (flag == "1")
$("#btnPrint").show();
else
$("#btnPrint").hide();
});
my javascript code
$().ready(function () {
$.ajax({
type: "POST",
url: "../WebService.asmx/GetDistricts",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
BindDist(msg.d);
}
});
});
as
function BindDist(msg) {
$.each(msg, function () {
$("#dropDist").append($("<option></option>").val(this['DistrictId']).html(this['Name']));
});
}
in server side i want to get value by dropDist.selectedItem.but i can't get value how to do it.
int DistrictId = Int32.Parse((dropDist.SelectedValue).ToString());
how i get the dropdown selected value in server side?any help me is highly appreciated.
You can't get selected value from dropdown if you adding options in javascript. Also, you lost SelectedIndexChanged event handler as well. If you need to fill dropdown on client and still have ability to use SelectedValue property and SelectedIndexChanged event you need to develop own ajax server control. Or you can use some like ComboBox from AjaxControlToolkit library.
Despite of all above, if you still want to use regular DropDown filled on client then you can get selected value on server as there: string dropDistSelectedValue = Request.Form[dropDist.UniqueID];
I used a Jquery truncator solution which is neatly written by Henrik Nyh to have a read more/less functionality. The script here
I wanted to modify this code to be able to keep track of read/unread status by updating database. I worote the code that does the database update in a webservice as follows.
[WebMethod]
public void updateReadStatus(int ID)
{
//code to update the database
}
I added the following to consume the webservice in the Jquery
function updateStatus(){
$.ajax({
type: "POST",
url: "WebServices/myWebService/updateReadStatus",
data: "{'ID': " + $("#lblID").Text + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnError
});
function OnSuccess(reuslt) {
alert(result.d);
}
function OnError(result) {
alert(result.status + ' ' + result.status);
}
}
//and i called this function on this line
full_node.find('a:last').click(function() {
truncated_node.show(); updateStatus(); full_node.hide(); return false;
//The user control that im using this scrip on has a repeater that contains a div that contains the paragraph to be truncated.
<div class="readmore">
<%# Eval("Message_Text")%>
<asp:Label ID="lblID" runat="server" visible="false"
</div>
The truncate script works fine and it gave me the functionality i want, read more/less. But i am not able to get the added functionality i wanted. I am getting "12030 unknown" error, i believe the problem is in the line data:
"{'ID': " + $("#lblID").Text + "}",
how can I bring the value of the parameter ID from the text value of the lable to pass it to the webservice?
text is a function, not a property, so you need to call it with ():
"{'ID': " + $("#lblID").text() + "}",
Also, if you want to call a given WebMethod via Ajax, you'll need to decorate it with the [ScriptMethod] attribute.
You don't say what lblID identifies, but you should either be doing:
$("#lblID").text()
or
$("#lblID").val()
See http://api.jquery.com/text/ and http://api.jquery.com/val/
Hi
I used jquery in my application and I have a problem but I think it is necessarly to look at this code :
$("#btnAddToBasket").click(function () {
var id = $("#ProductIDAtBasket").text();
var count = $("#BasketAddedValueText").val();
//ajax request
$.ajax({ type: "Post",
url: "Services/NewE_ShopServices.asmx" + "/" + "GetPrice",
data: "{" + "count" + ":" + count + ", goodcode : " + id + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: AjaxSucceeded,
async: true,
cache: false,
error: AjaxFailed
});
});
function AjaxSucceeded(result) {
var res = result.d;
res = res.split(';');
$("#spanFinalPrice").text(res[2]);
$("#spanAbsolutePrice").text(res[3]);
$("#spanDiscount").text(res[4]);
$("#spanCount").text(res[1]);
$("#AddBasketDiv").hide("slow");
}
function AjaxFailed(result) {
alert(result.responseText);
}
As you can see at the following there is ajax send method to web service I get the values and put results using ajaxsucceeded method into the page it works fine and suitable but my problem is that it is basket viewer and I want to be more permanent for example in this page when you go to other page and back to it the contains will be omitted I can use session and cookies in the webservice class but how I can read from jQuery code? what is solution is there any other solution ?
If I am understanding it correctly, you are adding things to a basket, but they are not persisting on other pages? I.E, you add a product to your basket, and then move to another page and the item is not in the basket?
If so you need to check a couple of things:
How are you storing the basket on the server side. Do you put the items in Session?
Are you reading from that basket to pre-populate the basket in a state before you add items in?
I just add another ajax method to my jquery script and put some sever side property and set them by ajax method that was easiest.
I have a user control that I'm creating that is using some AJAX in jQuery.
I need to call a function in the code-behind of my control, but every example I find online looks like this:
$("input").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetResult",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
//do something
}
});
});
This works fine if I have the method in the Default.aspx page. But I don't want to have the function there, I need the function in the code-behind of my control. How can I modify the url property to call the correct function?
I tried:
url: "GetResult"
but that didn't work.
The way to handle this is to have the webmethod in your page, then just pass the values directly to a control method with the same signature in your control - there is no other way to do this.
In other words, ALL the page method does is call the usercontrol method so it is really small. IF you have the same signature for multiple child controls, you could pass a parameter to tell the page method which one to call/use.
EDIT: Per request (very very simple example). You can find other examples with more complex types being passed to the server side method. for instance see my answer here: Jquery .ajax async postback on C# UserControl
Example:
Page method: note the "static" part.
[WebMethod]
public static string GetServerTimeString()
{
return MyNamespace.UserControls.Menu.ucHelloWorld();
}
User Control Method:
public static string ucHelloWorld()
{
return "howdy from myUserControl.cs at: " + DateTime.Now.ToString();
}
Client ajax via jquery:
$(document).ready(function()
{
/***************************************/
function testLoadTime(jdata)
{
$("#timeResult").text(jdata);
};
$("#testTimeServerButton").click(function()
{
//alert("beep");
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
dataFilter: function(data)
{
var msg;
if (typeof (JSON) !== 'undefined' &&
typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
url: "MyPage.aspx/GetServerTimeString",
success: function(msg)
{
testLoadTime(msg);
}
});
});
});
Note: the dataFilter: function(data)... part of the ajax is so that it works with 2.0 and 3.5 asp.net ajax without changing the client code.
You can't...WebMethods have to be in WebServices or Pages, they cannot be inside UserControls.
Think about it a different way to see the issue a bit clearer...what's the URL to a UserControl? Since there's no way to access them you can't get at the method directly. You could try another way perhaps, maybe a proxy method in your page?