How to use ajax to access code behind method with parameters - c#

Currently I have this...
public void lnkTag_Click(object sender, EventArgs e){
...
}
Which is attached to the click() event of link buttons, but the problem is this requires a form resubmission when the user tries to back in the browser after clicking one.
I'd like to turn this into an ajax call that passes in the text value of the link. So to have a method like this in the code behind:
public void lnkTag_Click(string linkText){
...
}
Where this method is accessed via ajax on a
$('myLinkButton').click(function() {
$.ajax...
})
Any thoughts? Thanks.

Do the following for sending the parameter value:
$('myLinkButton').click(function() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "yourpage.aspx/lnkTag_Click",
data: "{'linkText': '" + linkTextValue + "'}",
dataType: "json",
success: function(data) {
//do something if it's successful
},
error: function(jqXHR, textStatus, errorThrown) {
//do something if there's an error
}
});
});

Related

Disable ASP:dropdownlist based on the selection of another ASP:Dropdownlist.value

I have two asp.net dropdownlists that I want to manipulate clientside with Javascript.
These two dropdowns are inside a modal open: function()
When dropdown1.value == "me"
I want dropdown2.value to be disabled
How can I accomplish this?
$(document).ready(function () {
if (document.getElementById('<%=dropdown1.ClientID%>').value == 'Me')
document.getElementById('<%=dropdown2.ClientID%>').disabled = true;
});
(optional) Part 2 I need to set an entity framework value to null after dropdown2 has been disabled how could I accomplish this without a postback?
Part 1:
$(document).ready(function ()
{
if($("#<%=dropdown1.ClientID%>").val() == "Me")
$("#<%=dropdown2.ClientID%>").prop("disabled",true);
});
Part 2 :
You would need to make an ajax call to a code behind or webservice to do that.
.ASPX
$.ajax({
type: "POST",
url: "PageName.aspx/CodeBehindMethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
},
error: function (error) {
}
});
.ASPX.CS
[WebMethod]
public static void Test()
{
// Call EF code
}

Jquery to ashx not working event not fired

I am using the below code to call a ashx page. But it's not working for me. I have place my code here. I always got the error message message "Request Failed". Please help me..
<script type="text/javascript">
function CallLoginHandler(user, pass) {
alert(user);//Got value
alert(pass);//Got Value
$(function(){
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx?MainPage=GetUserDetails&Type=2&user=" + user + "&pass=" + pass + "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnComplete,
error: OnFail
});
return false;
});
}
function OnComplete(result) {
alert([result.Id, result.Name, result.Age, result.Department]);
}
function OnFail(result) {
alert('Request Failed');
}
</script>
remove these lines:
$(function(){ // <----remove this
return false; // and this
}); // and this too
Update to this function:
function CallLoginHandler(user, pass) {
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx", // updated url
data: { // pass your data like this since type is post
MainPage:"GetUserDetails",
Type:2,
user:user,
pass:pass
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnComplete,
error: OnFail
});
}
and also your url is not correct:
url: "../handler/JQGridHandler...... + pass + "",
// --here you have a blank `""` after pass-----^
and since your type: "post" so you can pass the data like this:
data: {
MainPage:"GetUserDetails",
Type:2,
user:user,
pass:pass
},
Separate your string into a javascript object to be encoded and sent to the server as JSON based on your content type. Also, get rid of $(function(){ in your function call, it's useless here.
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx';
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
MainPage: 'GetUserDetails',
Type: 2,
user: user,
pass: pass
}
success: OnComplete,
error: OnFail
});
If this doesn't work, then the issue is likely one of the following:
The URL address is wrong
The server is evaluating a GET as opposed to a POST request
The server expects, application/x-www-form-urlencoded but you've declared it's json
You have a routing issue
Note: Do not send your user and pass in query string.
function CallLoginHandler(user, pass) {
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx",
data: {
MainPage: 'GetUserDetails',
Type: 2,
user: user,
pass: pass
},
// DO NOT SET CONTENT TYPE to json
// contentType: "application/json; charset=utf-8",
// DataType needs to stay, otherwise the response object
// will be treated as a single string
dataType: "json",
success: OnComplete,
error: OnFail
});
});
}
Your handler.ashx file
using System;
using System.Web;
using Newtonsoft.Json;
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string user= context.Request.Form["user"];
//.....
var wrapper = new { d = myName };
// in order to use JsonConvert you have to download the
// Newtonsoft.Json dll from here http://json.codeplex.com/
context.Response.Write(JsonConvert.SerializeObject(wrapper));
}
public bool IsReusable
{
get
{
return false;
}
}
}
source

jquery postback using c# and asp.net returns null

I am attempting to use jquery to call a c# function when a button is clicked. What happens is the return variable (msg) is null.
The button code:
<button id="test1" runat="server">Get Text</button>
The JQuery code:
$(document).ready(function() {
$("#test1").click(function() {
$.ajax({
type: "POST",
url: "ServiceDirectoryAdd.aspx/GetCurrentDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
}
});
});
});
The C# function:
[WebMethod]
public static string GetCurrentDate()
{
return "foo";
}
As I said, the return variable, msg, returns null. Is there something I'm doing wrong?
EDIT: After placing a breakpoint in the C# function, it seems that the program is not entering the function.
Did you added script manager to page. If you not added it. Please add it and then script manager "EnablePageMethod" property to true.
Here is the link for that.
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
try with indexing the msg
alert(msg[0]); or alert(msg.d);
Have you tried a GET?
$.get("ServiceDirectoryAdd.aspx/GetCurrentDate", function(data){
alert(data || data.d);
});
And edit the webmethod to accept get
[WebMethod]
[ScriptMethod(UseHttpGet=true)]
public static string GetCurrentDate()
{
return "foo";
}

Calling a c# methode from javascript/jquery and get the result

I have a dialog in an ASP.Net,c# application.This dialog has a textbox.When I choose save I want to call a function from C# who makes some verifications in the database and then to get the result in javascript/jquery.If the inserted value is true I want to close the dialog other way to remain opened,but I can't succed to close the dialog box after i receive true from c# function.Below is the code:
ascx :
<div id="popup" title="Choose Delegate">
<label>Delegate<label><input type="textbox" value="" name="inputD" id=="inputD"/>
</div>
Javascript:
$('#btnAdd').click(function(e){
$('#divPopup').slow("show");
$('#divPopup').dialog({
height:150,
width:300,
modal:true,
buttons:{
"close":function(){$(this).dialog("close");}
"save":function(){
var obj=document.getElementid("inputD");
$.ajax({
type: "POST",
url: "add.aspx/check",
data: "{delegate: '" + obj.Value+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
rez= "OK";
$(this).dialog("close");
},
failure: function () {alert("FAIL"); }}); }
});
}
C#:
[WebMethode]
public static Boolean check(string delegate)
{
.....
return true;
}
C# methode returns corect value.
I try also this :
$('#btnAdd').click(function(e){
$('#divPopup').slow("show");
$('#divPopup').dialog({
height:150,
width:300,
modal:true,
buttons:{
"close":function(){$(this).dialog("close");}
"save":function(){
var obj=document.getElementid("inputD");
var rez ;
$.ajax({
type: "POST",
url: "add.aspx/check",
data: "{delegate: '" + obj.Value+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
rez= "OK";
},
failure: function () {alert("FAIL"); }
});
if (rez="OK")
$(this).dialog("close");
}
});
But it doesn't see the rez value in this case.
Thanks !
You can use an Ajax Call in your "save":function(e) and just check the returned value if true close dialog, else remain opened
Ajax calls are really simple to implement, I let you search that :)
You need a web-service on the server side. (preferably REST)
http://restsharp.org/ is an easy to use library for that.
Take a look at this question for more info.
In the front end you make an ajax call to you're REST api (I see you use jquery so it won't be that hard ;))

jQuery Get() to WebMethod not working

I'm trying to call the jQuery function $.get() to make a call to my WebMethod but it's only hitting the Page_Load event in the code behind. I can see the request being sent out in firebug to /admin/manage-users.aspx/deleteUser?u=user1 but it never hits the WebMethod.
jquery
$('#delete').each(function () {
$(this).click(function () {
var userName = $(this).closest('tr').find('span.userName').text();
$.get('/admin/manage-users.aspx/deleteUser', { u: userName });
});
});
aspx.cs
[WebMethod]
public void deleteUser() {
string userName = Request.QueryString["u"];
if(!string.IsNullOrEmpty(userName)) {
if(Membership.DeleteUser(userName))
Response.Redirect(Request.Url.ToString());
}
}
SOLUTION
I gave credit to bugz below because he pointed me in the right direction.
In order for your [WebMethod] to work your method within the aspx has to be static
Here is a link for more information
More Information
$.ajax({
type: "POST",
url: "'/admin/manage-users.aspx/deleteUser'",
data: "{'userName ' : '" + userName + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
//do something on success
},
error: function(ex) {
//do something on failure
}
});
Also on success if you are returning data or a variable make sure you use data.d for some reason when using jquery/ajax microsoft wants the .d at the end of the variable. This took me time to figure out.
Try this Im guessing when you debug the deleteUser Method never gets called.
var jqxhr = $.get("admin/manage-users.aspx/deleteUser", { userName: userName } function() {
alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });

Categories