I want to share a very basic and simple but a bit advance sample code on ASP.Net Ajax using JSON and JQuery. Now I want to change a control name or text based on server response data.
To demonstrate this thing I shall change my clicked button name based on server. This type of sample code is very easy to learn and you can use similar concept to develop solution for lots of requirement. Say you are developing some code where you have a button to 'Like' but after clicking on it the button name will change to 'Unlike', or in a social network one user will start following some group or person; so when user will click on 'Follow' button will be changed to 'Following' etc.
Lets have a look in to the code:
HTML for this solution as below -
in put id=
"btnClick"
type=
"button"
value=
"Click Me!"
Here button 'btnClick' text will be changed. Next look into the back-end C# code.
[WebMethod]
public
static
string
ChangeButtonNameJQuery(
string
btnName)
{
return
btnName+
" - changed from Server"
;
}
Very simple Web Method or WebService in page 'ChangeButtonName.aspx'. To declare a page method as WebService we need to use namespace 'System.Web.Services', which I have used in using namespace section. Besure this method is 'static' type and its 'public'. Return type of webservice is string and invoking with one string parameter 'btnName'.
Now look at the jQuery code.
"js/jquery-1.9.1.js"
>
"text/javascript"
>
$(document).ready(
function
() {
$(
"#btnClick"
).click(
function
() {
$.ajax({
type:
"POST"
,
url:
"ChangeButtonName.aspx/ChangeButtonNameJQuery"
,
data: JSON.stringify({ btnName: $(
"#btnClick"
).val() }),
contentType:
"application/json; charset=utf-8"
,
dataType:
"json"
,
success:
function
(msg) {
$(
"#btnClick"
).val(msg.d);
}
});
});
});
I have used here Jquery version 1.9.1 and calling my method when document becomes ready to execute which will call just after loading completion of page.
$(document).ready(
function
()
{
}
$(
"#btnClick"
).val(msg.d);
Thank you for visiting my blog. Happy coding.
No comments:
Post a Comment