Problem with jQuery selector and MasterPage - c#

I have a problem with a master page containing a asp:textbox that I'm trying to access using jQuery. I have read lot sof thread regarding this and tried all the different approaches I have seen, but regardless, the end result end up as Undefined.
This is the relevant part of the MasterPage code:
<p><asp:Label ID="Label1" AssociatedControlID="osxinputfrom" runat="server">Navn</asp:Label><asp:TextBox CssClass="osxinputform" ID="osxinputfrom" runat="server"></asp:TextBox></p>
When I click the button, the following code from a jQuery .js file is run:
show: function(d) {
$('#osx-modal-content .osxsubmitbutton').click(function (e) {
e.preventDefault();
if (OSX.validate()){
$('#osx-modal-data').fadeOut(200);
d.container.animate(
{height:80},
500,
function () {
$('#osx-modal-data').html("<h2>Sender...</h2>").fadeIn(250, function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{'from':'" + $("#osxinputfrom").val() + "','mailaddress':'" + $("#osxinputmail").val() + "','header':'Test3','message':'Test4'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$('#osx-modal-data').fadeOut(200, function () {
$('#osx-modal-data').html('<h2>Meldingen er sendt!</h2>');
$('#osx-modal-data').fadeIn(200);
});
},
error: function(msg){
$('#osx-modal-data').fadeOut(200, function () {
$('#osx-modal-data').html('<h2>Feil oppstod ved sending av melding!</h2>');
$('#osx-modal-data').fadeIn(200);
});
}
});
});
}
);
}
else{
$('#osxinputstatus').fadeOut(250, function () {
$('#osxinputstatus').html('<p id="osxinputstatus">' + OSX.message + '</a>');
$('#osxinputstatus').fadeIn(250);
});
}
});
},
So the problem here is that $("#osxinputfrom").val() evaluated to Undefined. I understand that the masterpage will add some prefix to the ID, so I tried using the ID from the page when it's run that ends up as ct100_osxinputfrom, and I also tried some other hinds that I found while searching like $("#<%=osxinputfrom.ClientID%>"), but it ends up as Undefined in the method that is called from the jQuery ajax method anyway. The third and fourth parameters to the ajay function that is hardcoded as Test3 and Test4 comes fine in the C# backend method.
So my question is simply: How can I rewrite the jQuery selector to fetch the correct value from the textbox? (before I used master pages it worked fine by the way)
Best regards
Daemon

It will be abit slower but why dont you try adding cssclass="bla" to your label and then get it with $('.bla').val(); ?

You should use the attribute ends with selector
Link
it would be $("id$='osxinputfrom'")

Related

Ajax using JQuery in ASP .NET c#

I am trying to use JQuery ajax in asp .net c#. The code I am using is ...
HTML FORM:
<div>
Your Name :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time"
onclick = "ShowCurrentTime()" />
</div>
JQuery Part :
<script type="text/javascript">
function ShowCurrentTime() {
//alert(window.location.pathname);
$.ajax({
type: "POST",
url: "Display.aspx/GetCurrentTime",
data: '{name: "' + $("#< %=txtUserName.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
</script>
CS PArt:
using System.Web.Services;
This part below is under partial class which inherits from Page class.
[WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello "+ name +"! " + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
Problem:
It is not working. Please let me know if I am missing any setting or any name space. Or any thing. URL I Put in ajax Call is correct as I verified it by
var pathname = window.location.pathname; I supplied data also while calling ajax.
Maybe changing
failure: function (response) {
alert(response.d);
}
to
error: function (response) {
alert(response.d);
}
Will help find the issue.
I don't see a failure callback in the docs - http://api.jquery.com/jquery.ajax/
The things I can see right off the bat:
$.ajax doesn't take a "failure" parameter, but rather "error." Even
then, you should be using .done() and .fail() instead (see
http://api.jquery.com/jQuery.ajax/)
Your error handling function will be triggered when your page method
throws an exception. The first parameter is a jqXHR object, not a
JSON response from .NET (see the same link as from #1).
Your page method should not go UNDER the page class, but within it.
JQuery has some error
$("#< %=txtUserName.ClientID%>")[0].value
need to be
$("#<%=txtUserName.ClientID%>")[0].value
or
$("#<%=txtUserName.ClientID%>").val()

WebMethod never be called in asp.net

I am using jQuery to call C# code behind methods. Here is my ascx file code:
ASPX
<div class="dnnFormItem">
<asp:LinkButton id="cmdLogin" resourcekey="cmdLogin" cssclass="dnnPrimaryAction" text="Login" runat="server" />
JQuery
<script type ="text/javascript">
$(document).ready(function () {
$('#<%=cmdLogin.ClientID %>').click(function () {
$.ajax({
type: "post",
url: "Login.ascx/ServerSideMethod",
data: "{sendData: '" + ID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("successful!" + result.d);
}
});
});
});
</script>
And here is my C# code:
[WebMethod]
public static string ServerSideMethod()
{
return String.Format("Hello");
}
Please help me out to solve this. My WebMethod function in C# is never be called.
your ServerSideMethod() is expecting a parameter sendData. have you tried using an aspx page or an asmx rather than an ascx
You are passing a parameter but the web method doesn't take any parameters, so is likely throwing an exception. Use the error function to find this for sure. This can be done similar to your success callback. Information about that can be found in the Jquery documentation: http://api.jquery.com/jquery.ajax/
for data: "{sendData: '" + ID + "'}",
check if ID really exist??? if if you want to really pass the parameter to ServerSideMethod else remove this line in case you are not passing this parameter to ServerSideMethod.
and change WebMethod,pass parameter sendData
[WebMethod]
public static string ServerSideMethod(string sendData)
{
return String.Format("Hello");
}
url: "Login.ascx/ServerSideMethod"
You'll have to move your "service" to an asmx (or aspx, ashx) file - WebMethods can't be in UserControls..
I've seen some "workarounds" but IMHO, they're not really workarounds per se...or should I say "hacky" and ends up being more convoluted than just going asmx
Hth...

JQuery code to call a c# method not working

I am calling a C# function from JQuery but it is giving error.
The JQuery function is written in ascx file and C# function to be called is written in that page's code behind. I am loading the user control into an AJAX tab on tab change event.
Googling, I got that I can not call C# function written in user control. So I written a function in host page(ASPX) and this function is calling my user control function.
But the AJAX request is some how failing, I don't know where. But interesting thing is I have kept a debugger in the error function and I checked the error object.
Status is 200, Status is OK, readyState is 4
and ResponseText is the markup of the page. This means the page is served but the kept the break point in the C# function. It never hits.
I have no idea what's happening. Also this is the first time I am calling a C# function from front end. I don't have detailed idea of what happens under the hood. Please help. Below is the code:
JQuery
$(function () {
$(".hint ul li").click(function () {
// remove classes from all
$(".hint ul li").removeClass("active");
// add class to the one we clicked
$(this).addClass("active");
//Ankit J, Implement logic to call jquery
var Availability = this.childNodes[0].innerText.trim();
debugger;
$.ajax({
type: "POST",
url: "../Pages/MyPage.aspx/CallUCMethodFromJQuery",
data: "{'sAvailability' : 'Availability'}",
dataType: "json",
success: fnsuccesscallback,
error: fnerrorcallback
});
});
});
function fnsuccesscallback(data) {
alert("success-->" + data.d);
}
function fnerrorcallback(result) {
debugger;
alert("error-->"+result);
}
ASPX page's code behind function
[System.Web.Services.WebMethod]
public void CallUCMethodFromJQuery(string sAvailability)
{
MyNamespace.UserControls.ControlName m = new UserControls.ControlName();
m.EditAvailabilityValue(sAvailability);
}
And then the UserControl's code behind
public void EditAvailabilityValue(string sAvailability)
{
}
Sorry for not mentioning.... JQuery is in the User Control because the source of click event is a li element which is in the User Control. Also the UserControl is in a folder UserControls and the host page is in the Pages folder and both these folders are in root folder.
Add contentType: "application/json; charset=utf-8" attribute to your ajax call:
$.ajax({
type: "POST",
url: "../Pages/MyPage.aspx/CallUCMethodFromJQuery",
data: "{'sAvailability' : 'Availability'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: fnsuccesscallback,
error: fnerrorcallback
});
then change EditAvailabilityValue method in the user control to static:
public static void EditAvailabilityValue(string sAvailability)
{
}
and change CallUCMethodFromJQuery method in the aspx page code behind to static so it can be called using jQuery:
[System.Web.Services.WebMethod]
public static void CallUCMethodFromJQuery(string sAvailability)
{
MyNamespace.UserControls.ControlName.EditAvailabilityValue(sAvailability);
}

Calling Code Behind Method From Jquery

I am using Asp.net/C# in my project , i have a requirement where in the user enters a name and the details of that person is displayed asp.net gridview ,,,, i am planning to use html button instead of asp.net button because the results displayed will be in tab...However the function which will populate the gridview is in code behind ,, so my question is how will i call that method from jquery,,, is that possible.Or is there any better way of doing this......
Thanks in advance
Have look to this post which describe you how to call function of code behind : Calling Server Side function from Client Side Script
Cs File (codebehind)
[WebMethod]
public static string IsExists(string value)
{
//code to check uniqe value call to database to check this
return "True";
}
Javascript/jQuery
function IsExists(pagePath, dataString)
{
$.ajax({
type:"POST",
url: pagePath,
data: dataString,
contentType:"application/json; charset=utf-8",
dataType:"json",
error:
function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
},
success:
function(result) {
alert( result.d);
}
}
});}
var pagePath = window.location.pathname + "/IsExists";
var dataString = "{ 'value':'ab" }";
IsExists(pagePath, dataString);

Using jQuery AJAX to call ASP.NET function in control code-behind instead of page code-behind

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?

Categories

Resources