Accessing page objects through static methods - c#

I am using asp.net datepicker. Then executing a static event when a user clicks on a date through jquery like such:
<script>
$(document).ready(function () {
$("#datepicker").datepicker({
onSelect: function (dateText, inst) {
$("#<%= lblDate.ClientID %>").text("Are available on " + $('#datepicker').datepicker({ dateFormat: 'dd-mm-yy' }).val());
$.ajax({
type: "POST",
url: "Schedule.aspx/DisplayAvail",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Do something interesting here.
}
});
}
});
});
</script>
Code behind:
[WebMethod]
public static void DisplayAvail()
{
//Grab data from db to check avail from this date
}
Which works fine. But, from this static method there is no way to access page level objects. How can I send data from this method to the page?

Have a look here. You can get this via NuGet
http://james.newtonking.com/projects/json-net.aspx
Once you have the NewtonSoft Json dll added as a reference to your project which contains the webmethod, you can use JSONConvert to serialize your available dates and send it client side.
public IEnumerable<string> AvailableData {get; set;}
[WebMethod]
public static void DisplayAvail()
{
this.AvailableData = GetRequiredData();
this.AvailableData = JSONConvert.SerializeObject(this.AvailableData);
}
And on the client side, you can do:
$(document).ready(function () {
$("#datepicker").datepicker({
onSelect: function (dateText, inst) {
$("#<%= lblDate.ClientID %>").text("Are available on " + $('#datepicker').datepicker({ dateFormat: 'dd-mm-yy' }).val());
$.ajax({
type: "POST",
url: "Schedule.aspx/DisplayAvail",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var arr = <%= this.AvailableData %>;
$.each(arr, function(index, value) {
// Do something with the data
});
});
}
});
}
});
});

I decided the best rout to go is to use JQuery load() function to load an external page into the current page as such:
...Jquery
$("#GetData").load("getData.aspx?GetDate=012420012");
...html
<div id="GetData">
...
</div>
Thanks for all your feedback, but I think that this is the best way to go. Cheers! :)

You could try using PageMethods():
This is a simple tutorial Simple PageMethods example.
And also you need to do this:
<asp:ScriptManager ID="ScriptManager" runat="server" EnablePageMethods="true" />
;)

Related

calling function in the javascript written in webpage(.cs)

I have function on .cs page
[System.Web.Services.WebMethod]
public static string getdata()
{
ProductBAL objbal = new ProductBAL(); // Calling class
int i = 0;
i = objbal.get_last_orderid(); //Select query
i = i + 1;
ProductDAL objdal = new ProductDAL(); // Calling class
objdal.insert_new_orderid(i); //Insert query
HttpCookie orderid = new HttpCookie("orderid");
orderid.Value = "MP_" + Convert.ToString(i);
Response.Cookies.Add(orderid);
Response.Cookies["orderid"].Expires = DateTime.Now.AddHours(5);
string abc=Convert.ToString(i);
return abc;
}
My Html page code is
<head id="Head1" runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>calling function from .cs</title>
<script language="javascript" type="text/javascript">
function Submit1_onclick() {
$.ajax({ type: "GET", url: "default.aspx/getdata()", success: function (data) { });
alert("Done");
}
</script>
</head>
<body>
<form name="ecom" method="post" action="https://www.google.co.in/">
<input id="Submit1" type="submit" name="submit" runat="server" value="Submit" onclick="return Submit1_onclick()">
</form>
</body>
I am trying to call my web side function to client side on submit click.
Am I missing something? Please give a demo from my above code
function Submit1_onclick() {
// alert("Hello");
$.ajax({
type: "GET",
url: 'demo.aspx/getdata',
data: "{}",
//"{character:'M'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert(data.d);
//alert("success");
alert("This is ajax call:");
},
error: function() {
//alert(Error);
alert("something went wrong");
}
});
// alert("Done");
}
[WebMethod()] //U have to declare this method as a web method
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string getdata()
{
On your url try : "PageName.aspx/MethodName". Also check out this blog post by Dave Ward :
Using jQuery to directly call ASP.NET AJAX page methods
Below line is error prone. do not include "()" in url method name.
$.ajax({ type: "GET", url: "/getdata()", success: function (data) { });
Replace above line with
$.ajax({ type: "GET", url: "/getdata", success: function (data) { });
See the following working example
// Code behind method declared static
[WebMethod]
public static string GetSquare(String value)
{
return "hello" + value;
}
your button whose click this has to be done
<input type="button" id="button" value="Chnageurl" onclick="ajaxcall()" />
script for this
<script type="text/jscript">
function ajaxcall(e) {
$.ajax({
type: "POST",
url: "Default.aspx/GetSquare",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ value: "test" }),
dataType: "json",
success: function (value) {
alert(value.d);
},
error: function () { alert("Ajax Error"); }
});
};
From your comments I have gathered that you are verifying if this method is working by checking for new entries in a database table. The data in the database could be missing for other reasons rather than the query. To verify, try a more simple web method, and go from there.
eg,
Html :
<input id="submit" type="submit" name="submit" value="Submit" onclick="return submitClick();" />
Javascript :
function submitClick() {
$.ajax({
type: "POST",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "default.aspx/getdata",
success: function (data) {
console.log(data);
alert("success" + data);
},
error: function () {
alert("something went wrong");
}
});
return false; // Note: the return false will prevent postback
}
C#
[System.Web.Services.WebMethod]
public static string getdata()
{
return "Hello World!";
}
If you do not see a success response, then the problem is indeed with your javascript, or rather with the site setup which is somehow preventing callbacks from javascript.
If the method succeeds then it is likely that your database insertion script is raising an error and you should step through it to see that cause.

What is wrong with this JQuery AJAX code

I was facing some problem with AJAX code. I was using MVC3 for our project. My requirement is bind the dropdown value using AJAX when page load. What happens when loading the page, the AJAX request send to the controller properly and return back to the AJAX function and binds the exact values in dropdown. But sometimes (When page refreshed or first time load) its not binding retrieved value. Rather its showing default value. Pls see my code and suggest me where i am doing wrong.
Edit: Even i tried to use async property to false. Its not at all send to the controller action method for getting the data.
Code
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("GetUser", "Invoices")',
data: "{'id':" + JSON.stringify(currval) + "}",
dataType: "json",
async: true,
success: function (data) {
$("#User-" + curr).select2("data", { id: data.Value, Name: data.Text });
$(this).val(data.Value);
}
});
Thanks,
Let's say your Action method is below
public JsonResult hello(int id)
{
return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}
and JQuery should be like below
<script language="javascript" type="text/javascript">
$(document).ready(function () {
var currval = 2;
$.ajax({
url: 'URl',
async: true,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ id: currval }),
success: function (data) {
}
});
});
</script>
You are declaring your data property incorrectly. Try this:
data: { id: currval },

Redirect back to Default.aspx

I have a default.aspx (c#) page which has a simple Post AJAX call to a WebMethod that returns a JSON object, so that I can then populate a DataTable. All worked fine until I introduced a login page. Now, when a user is redirected to the Default page, after logging in, the Post never appears in FireBug.
This is my AJAX call:
$.ajax({
type: 'POST',
url: '/Default.aspx/GetValueDateSummary',
contentType: 'json',
data: {},
sucess: function (response) {
renderTable(response.d);
},
error: function (errMsg) {
$('#errorMessage').text(errMsg);
}
});
});
with the code behind being:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public static List<ValueDateSummary> GetValueDateSummary()
{
some code in here.....
return drList;
}
sucess: function (response) {
should be
success: function (response) {
Are you using a ScriptManager object? If so, I believe that you need to enable page methods for it to work.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
Ok, i sorted it.
here is the complate Ajax call, seems i was missing the proper contentType and dataType
$.ajax({
type: 'POST',
url: 'Default.aspx/GetValueDateSummary',
contentType: 'application/json;charset=utf-8',
dataType: 'json',
success: function (response) {
console.log(response);
alert(response.d);
renderTable(response.d);
},
error: function (errMsg) {
$('#errorMessage').text(errMsg);
}
});

Ajax Autocomplete using jQuery

I have the following code to retrieve departments names from db I have problem formatting CSS of data like background and font color
<script type="text/jscript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "/AjaxLoad.asmx/GetBrands",
dataType: "json",
data: "{}",
contentType: "application/json; charset=utf-8",
success: function(data) {
var datafromServer = data.d.split(":");
$("[id$='tbBrands']").autocomplete({
source: datafromServer
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
}
</script>
<div id="ajaxbrands">
<input id="tbBrands" runat="server" />
</div>
Any idea how to add text, like <p > or <div> to each list item?
I can think on 2 options:
1.Add it in your php code (like rdlowrey aadvised),
for instance:
$query = mysql_query("SELECT * FROM brands");
while($brand = mysql_fetch_array($query))
{
echo "<p>".$brand['name']."</p>";
}
2.Use jquery to do it.
"Split" converts your string to an array of sub-strings.
You should edit the autocomplete function so it will add each sub-string the desirable code. Add the function's code for more help.
Well, i assume you are using .NET, so, i wont mess around with server side code.
You can add this to your success callback function:
success: function(data) {
var datafromServer = data.d.split(":");
for(var item in datafromServer){
datafromServer[item] = '<p class="whatever">' + datafromServer[item] + '</p>';
}
$("[id$='tbBrands']").autocomplete({
source: datafromServer
});
},
The for loop added will surround every item in the array, with a p, or div, or whatever.

Jquery ajax autocomplete calling a method for data

$(function () {
$("#tbNominalAccounts").autocomplete({
source: function (request, response){
$.ajax({
url: "TestPage3.aspx/GetUserNominalAccounts",
type:"POST",
datatype:"json",
data :{ searchText : request.term},
success: function(data)
{
response(
$.map(data, function(item)
{
return { label: item.NominalAccount, value:item.NominalAccount, id:item.NominalAccount}
}))
}
})
}
});
});
Added breakpoints and it hits the ajax call but when i put a breakpoint on the method GetUserNominalAccounts it doesent even reach it!! Any ideas of why its not posting?!
I have a textbox with an ID of #tbNominalAccounts just for background information
Reformat your data like so:
pString = '{"searchText":"' + request.term + '"}';
$.ajax({
data: pString,
...
and your server side code should have been properly "decorated" to allow page access.
Thought I would add some code from a working sample using asp.net: you might need this converter for generic handling of the asp.net data:
dataType: "jsond",
type: "POST",
contentType: "application/json",
converters: {
"json jsond": function(msg)
{
return msg.hasOwnProperty('d') ? msg.d : msg;
}
},
EDIT: And for the use of the return value:
focus: function(event, ui)
{
return false; // return "true" will put the value (label) from the selection in the field used to type
},
try putting a contentType in the ajaxRequest:
contentType: "application/json; charset=utf-8",
I've noticed that when using jQuery Ajax the default content Type application/x-www-form-urlencoded doesn't work well enough.

Categories

Resources