populate dropdownlist on button click using jquery - c#

In my application ,I have a dropdownlist which is to be populated on button click.I tried some code which is working fine on document.ready but its not working on button click..
$(document).ready(function () {
$("#<%=btn.ClientID %>").bind('click',function () {
//
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "gridpaging.aspx/binddropdown",
data: "{}",
dataType: "json",
success: function (data) {
$.each(data.d, function (key, value) {
$("#ddl").append($("<option> </option>").val(value.UserId).html(value.UserName));
});
//
},
error: function (result) {
alert("Error occured");
}
});
});
});
Please let me know where i went wrong..Thanks in advance..

It looks like you are mixing up two techniques here. One is ejs: <%=btn.ClientID %>, which is a templating engine to serve up dynamic content. The other is your jquery. What may solve your issue is to add a class to that button, rather than relying on your btn.ClientID, and then use $(".myClass").bind('click', function() ...
See if that solves your problem. If not, I'll need a bit more information. Is the ejs being compiled on the server side or on the client side? Are you using backbone or some kind of front end framework that's compiling the ejs?

yourdeveloperfriend is almost right, except <%=btn.ClientID %> is not ejs, but asp.net snippet which is most probably used in the wrong place. I can imaging only one scenario in which this could work, and that is when this JS code is located in you aspx file, but most probably you have it in a separate js file. So do what yourdeveloperfriend said, and put a class on the button, and use that as a selector in your JS.

I also had this same issue and solved it by changing the id setting
$("#ddl")
to
$('#<%=ddl.ClientID%>')

Related

Sending data from controller to javascript using Linq 500 internal server error mvc2

C#
public ActionResult SimpleQuery()
{
ClientDataContext dc = new ClientDataContext();
var userResults = from u in dc.TS_Trucks select u;
return Json(userResults.ToList(), JsonRequestBehavior.AllowGet);
}
Javascript
$.ajax({
url: '#Url.Action("SimpleQuery")',
type: 'GET',
dataType: 'json',
success: function (data) {
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
I don't even use the data in the JavaScript, something about the way I'm passing it is probably the problem but can't seem to figure it out.
you need to specify the controller for your url helper. The server error is from trying to locate your action. Try this for the ajax url:
'#Url.Action("SimpleQuery", "<ControllerForYourActionHere>")'
Internal Error usually infers bad URL address.
In this case, url parameter is not set to right value.
First, you need to check which Router map to this function: SimpleQuery
Then, use that address to fill in url parameter.
Also, I don't think '#Url.Action("SimpleQuery", "<ControllerForYourActionHere>")' will work if you put
it in javascript file. It might works in cshtml file.
So, the conclusion is when you are doing frontend programming, use absolute link will be a good idea.
It make sure you hit the right address at the first time.

Is there a way to capture JavaScript PageMethods calls with jQuery? (To show Loading Screen)

I'd like to know if someone knows a way, using jQuery, to capture PageMethods calls made from JavaScript in order to show a loading screen when a call begins and to hide it when it ends (when the PageMethod responds).
I know there are ways to capture ajax calls when they are made like this:
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
but is there a way to capture them and then do something when they are called like this?
JavaScript
PageMethods.serverSideMethod(responseFromServer);
CodeBehind
[WebMethod()]
public static string serverSideMethod()
{
return response;
}
I'm using jQuery 1.9.2, programming in C# and need this script to be compatible with IE6.
it's almost the same,use this url in jQuery
url: "PageName.aspx/serverSideMethod",
insert your method name without parantheses,it should work.
Edit:
you can capture start and complete event with using these ajax events:
$.ajax({
beforeSend: function(){
// Handle the beforeSend event
},
complete: function(){
// Handle the complete event
}
// ......
});
Then you can show or hide whatever you want... here is the full documentation: http://api.jquery.com/Ajax_Events/
You can just show the loading message right after or before the PageMethod call and then hide it in the callback:
PageMethods.serverSideMethod(responseFromServer);
//Show loading using jQuery Here
function responseFromServer(results){
//process results
//hide loading using jQuery
}
UPDATE:
Have you tried Sys.WebForms.PageRequestManager beginRequest Event and endRequest Event: http://msdn.microsoft.com/en-us/library/bb397432(v=vs.100).aspx and http://msdn.microsoft.com/en-us/library/bb383810(v=vs.100).aspx

Handsontable ASPX Code behind method for LOADING data to grid

In a previous post Handsontable Grid - loading and saving data from aspx web page I solved the "ajax data transfer to the server for Saving" with help from Stephen B. Burris Jr, for which many thanks. I have been unable to get the reverse process to work - that is the loading of data from the server to the grid. I am using sample code from GitHub for the client-side javascript code, but what I am not clear on at all is how the data needs to be "packaged" in response to the ajax call. I would be very greatful if someone could show me the structure of the code-behind method. Below is the javascript code with the ajax call:
var handsontable = $container.data('handsontable');
$(document).find('button[name=load]').click(function () {
$.ajax({
url: "Default.aspx/getJSData",
dataType: 'json',
type: 'GET',
success: function (res) {
handsontable.loadData(res.data);
$console.text('Data loaded');
},
error: function () {
$console.text('Load error');
}
});
});
Have a look at this post
It is a working solution using WCF.
You haven't stated what technologies it needs to be, but I noticed the C# tag.
I hope it helps.

unable to render Json string on client side

ascx.cs
protected string BindData()
{
List<Product> products = product.GetRepeaterData(prod);
string json = JsonConvert.SerializeObject(products);
return json;
}
ascx
<script type="text/javascript" language="javascript">
function doSomething() {
$.ajax({
type: "POST",
url: "/ProgramListSimple.aspx/BindData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg);
}
});
};
I am not able to see any alert ..I dont know if the ajax function is doing what it is suppose to do..this code is for user control & not on the aspx page does that matter? while debugging I am able to see the serialized data in json string. Its just that its not rendering on the client side....working on it since morning now I need some help please..any examples or any doc can also be useful..
You have to use the d property
alert(msg.d);
If you are using Chrome or Firefox to debug use the following to inspect a JavaScript object:
console.log("%o", msg);
In Chrome press Ctrl + Shift + J to show the developer console
I created a new aspx page. Transfered all the code behind logic to the aspx.cs from ascx.cs. The just called the url of the aspx page from my ascx page using ajax callback
type: "GET",
url:'<%=VirtualPathUtility.ToAbsolute("~/ProgramListSimpledetail.aspx") %>',
data: dataObject,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data)
I just added a small part of the fix that is very important for this to work other then this there were bunch of things that were added to make the ascx page inherit the properties from the apsx page.... but I think that was mainly related to my code...so I hope this helps someone in future...thanks for all those who tried to contribute..

jQuery Postback with Webforms

We're redevloping a major section of our website and rather than use a 90k AJAX file I'd rather use a 19K jquery script.
I've seen the following articles;
Using jQuery for AJAX with ASP.NET
Webforms
jQuery autocomplete in ASP.NET webforms?
Autocomplete with ASP.Net MVC and
JQuery
The thing I don't get is how to do a postback to a specific method in either the code behind or another class.
I know in ASP.NET-MVC I can post back to a controller / action. How do I call a particular method in WebForms?
Something along the lines of; $.post("class and action", ( param:value}......
Any thoughts, code etc???
It is very easy to call specific methods in code-behind. Here is nice article with all the details by Dave.
Simply declare a method like this:
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
This is all you need in jQuery:
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg, status, xhr) {
// Do something interesting here.
}
});
Caveats:
WebMethod must be on a static method
Must stringify posted data if sending anything (i.e. JSON.stringify(yourDataObject)), will be deserialized according to method parameters
msg is the response, the return result from your method is in the property msg.d

Categories