Calling code behind function on dynamically generated href - asp.net

I am generating
<a href="...">
dynamically in a code behind. When I click on the link it needs to run a sub from the code behind and also I need to know which link actually triggered that code behind function.
This is my code behind (dynamically generating link) which is then displayed in div. I literally dump this (below code) as a string into a div:
<a href='#'
id='" + i.MemberId.ToString() + "'
Text='Click Me'
onServerClick='Check_Clicked'
runat="server">Click Me
</a>
And this is what I need to call:
Sub Check_Clicked(sender As Object, e As EventArgs)
Me.div_result.InnerHtml = "TEST"
End Sub
UPDATE:
Okay I added the following to my project:
<script type="text/javascript">
$(document).ready(function () {
$('#inboxLink').click(function () {
$.ajax({
type: 'POST',
url: 'inbox.aspx/GetSomething',
data: '{ test1: "somevalue" }',
ContentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("Success");
},
error: function (data) {
alert("Fail");
}
});
});
});
</script>
and then
<System.Web.Services.WebMethod()> _
Public Shared Sub GetSomething()
Me.div_result.InnerHtml = "TEST"
End Sub
but there are more problems In the code behind
'Me' is only valid within an instance method.
so I am not sure the way I am approaching this problem might be wrong?

Generating an element at the client side with runat="server" will not make it a server control. You better implement an AJAX based architecture.
Generate your client side anchor element (I'm using jquery here)
$('<a />', {
text:'Click Me',
id:'<whatever you like>',
click:function(){ makeCallToServerWithYourData(yourData); }
}).appendTo('yourTargetDivSelector');
So that's it if you want to call a server method.
If you just want to change the content of a div when you click on the anchor tag, as in your sample code, just replace the click event handler with whatever you want.
Please mark as answer if it helped you.
Thank you :)

Related

Getting Information from Console.log and displaying it in div

Currently I am stuck I want to return the title, plot and poster using themoviedb api I have no idea how to start the coding for this
Currently when i run a search the information is display in the console log of the browser i want to take that information and style it into a table format nothing fancy just the title and poster need help no clue where to start
doc site here http://docs.themoviedb.apiary.io/#get-%2F3%2Fsearch%2Fmovie
<html>
<head>
<title>Sample Seach</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var url = 'http://api.themoviedb.org/3/',
mode = 'search/movie',
input,
movieName,
key = '?api_key=My API KEY HERE';
$('button').click(function() {
var input = $('#movie').val(),
movieName = encodeURI(input);
$.ajax({
url: url + mode + key + '&query='+movieName ,
dataType: 'jsonp',
success: function(data) {
console.log(data);
}
});
});
});
</script>
</head>
<body>
<input id="movie" type="text" /><button>Search</button>
</body>
</html>
output looks like this it returns objects under a movie title in his chase 300
error when running each staement
Something like this:
$.ajax({
url: url + mode + key + '&query='+movieName ,
dataType: 'jsonp',
success: function(data) {
var table = '<table>';
$.each( data.results, function( key, value ) {
table += '<tr><td>' + value.original_title + '</td><td>' + value.release_date + '</td></tr>';
});
table += '</table>';
$('.myelement').html(table);
}
});
You don't read from the console. It's just for outputting debug information. The AJAX call basically returns an JavaScript object (whose structure you can see in the the console).
Access the data from it just like from any other JavaScript object (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects if you need to learn how) and work with that.
EDIT: If you need to know how to display the data on the web page, you need to learn about the DOM. See for example: http://www.elated.com/articles/javascript-dom-intro/

How to run run a post url?

What i am trying to do is basically run a script and post data to a page but the page is not on the server. So i dont want to run a redirect, just run a webpage in the back when the user clicks on a button?
I have tried...
set httpRequest = CreateObject("WinHttp.WinHttprequest.5.1")
Dim var1
var1 = Request("username")
on error resume next
httpRequest.Open "POST", "http://www.example.com", True
httpRequest.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
httpRequest.send var1
set httpRequest = nothing
But this doesnt seem to work. So i want to built the url http://www.example.com?username and run it?
The easiest way is to include a reference to the jQuery script libraries and use
.ajax
http://api.jquery.com/jQuery.ajax/
a call is simply:
<html>
<head>
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" ></script>
</head>
<body>
bip
<div id="result"> results to get replaced here</div>
<div id="msg" style="color:Red">any errors will show here</div>
<input type="button" value="click me" id="loadButton" />
<script language="javascript" type="text/javascript">
//ensure jQuery is loaded before calling script
$(document).ready(function () {
alert('ready');
$('#loadButton').click(function () {
alert('Handler for .click() called.');
$.ajax({
url: 'yoursite/yourpage',
error: function (xhr, ajaxOptions, thrownError) {
alert('doh an error occured. look at the error div above : )');
$('#msg').html(xhr.status + ' ' + thrownError); ;
},
data: "{'someparam':'someparamvalue','someparam2':'someparamvalue2'}",
success: function (data) {
$('#result').html(data);
alert('Load was performed.');
}
});
});
});
</script>
</body>
</html>
Your problem is most likely this line:
httpRequest.Open "POST", "http://www.example.com", True
Your "True" there is saying run in asynchronous mode, i.e. don't wait for the response before carrying on. You are then destroying the object immediately so the request is never going to get very far. Change that "True" to a "False" and you should see the result hit the other server.
Edit 1:
Also noticed you are not formatting the POST data correctly, it should take the traditional url formatted foo=bar, so the send line needs to be modified like so:
httpRequest.send "name=" & var1
Sorry I didn't spot this first time!
Edit 2:
Here is an example of a working GET transaction with WinHttpRequest:
Function GetHTTP(strURL)
Set objWinHttp = Server.CreateObject("WinHttp.WinHttpRequest.5.1")
objWinHttp.Open "GET", strURL, False
objWinHttp.Send
GetHTTP = objWinHttp.ResponseText
Set objWinHttp = Nothing
End Function
If you do really just need a GET transaction, you can use the following with this function:
strResponse = GetHTTP("http://www.example.com/?name=" & Request("username"))
And as you don't need the response, just ignore strResponse from there on in.
Reference:
NeilStuff.com - Open Method

How to call a serverside method using jquery?

I'm trying to call a server side method, using jquery, on the textchange event of a textbox which is generated dynamically on the clientside (I dont know how to fetch the id of this). Can somebody help me to do this stuff? The script im using is as follows:
<script type="text/javascript">
$(init);
function init() {
$('#test').droppable( //Div Control where i'll be dropping items
{
drop: handleDropEvent
});
$('a').each(function(idx, item) {
$(item).draggable({ cursor: 'move', helper: 'clone' })
});
}
function handleDropEvent(event, ui) {
var draggable = ui.draggable;
document.getElementById('test').innerHTML += addColumn(draggable.attr('text')) + '<br>';
}
$('.textChangeClass').live('change', function() {
/* Evokes on the text change event for the entire textboxes of class .textChangeClass. Is it possible to specify the dynamic textbox generated # clientside here? (like for e.g. : $('#mytextbox').click(function () ) */
$.ajax({
type: "POST",
url: "Webtop.aspx/ServerSideMethod", //This is not getting called at all.
data: "{'param1': AssignedToID}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function(msg) {
alert("From Server");
}
})
});
});
function addColumn(column) {
var iHtml;
//This is how i'm generating the textboxes along with a checkbox bound by a div.
iHtml = '<div id="dv' + column + '" width="100px;" height="20px;" padding: "0.5em;"> ' + '<span title="ToolTipText">' + '<input type="checkbox" id="cb' + column + '" value="' + column + '" /> <label for="cb' + column + '">' + column + '</label></span><input class="textChangeClass" type="text" id="aln' + column + '"> </div>';
return iHtml
}
</script>
I think you have an extra "});" although this probably isn't the problem.
What is "AssignedToID"? Try adding single quotes around that. I seem to remember having a weird problem a couple years ago related to quoting in the json.
Can you see the request in Fiddler/firebug/etc? Is the content correct?
You should be careful of your use of inferred semi-colons too. If you ever minify your javascript (yeah, I know this is embedded, but I'd like to hope that one day it will be moved to a seperate js file) you're eventually going to have a problem. Imagine some other developer comes along, does some refactoring and needs to add a return value after the ajax call.
$.ajax({...})return foo}
EDIT
Fiddler/Firebug Net panel are your friends... They will allow you to inspect the request and the response from the server. This way you don't have to add the error handler (although you may want to for other reasons eventually)
EDIT
To answer the other part of your question, you can access the textbox for which the change event was triggered through the use of the 'this' keyword inside of the event handler.
$('.textChangeClass').live('change', function(event) {
//Note that the 'event' parameter has interesting things in it too.
var changedText = $(this).val();
alert("The value in the textbox is: '" + changedText + "'");
var data = {
param1: changedText
};
$.ajax({
...
//Using json2 library here to create json string
data: JSON.stringify(data),
...
});
});
Note that I added the optional 'event' parameter to the event handler. It has interesting things in it and it's something that is often overlooked by people who are new to jQuery. Read about it here.
You need to write you code of adding the event to textbox after generation of textbox otherwise it's not get fire.
add text box
After that write code to add event to text box or bind event to text box
just follow the above step will do your work
EDIT
Add the error function to your ajax call you will get the error ... will allow you to proceed further
$.ajax({
type: "post", url: "/SomeController/SomeAction",
success: function (data, text) {
//...
},
error: function (request, status, error) {
alert(request.responseText);
}
});

Problem binding jqGrid in ASP.NET

I am new to using jqGrid and jquery.I am not able to bind my json data which I retrive from the webmethod onto the jqGrid.
I have also used firebug to cross verify and i am receiving data from it. Some help regarding this will be great. I would aslo like to know if any other references needs to be added.
following is the code that I have implemented.
PAGE METHOD
[WebMethod]
public static string GetData()
{
Customer Cone = new Customer();
Customer Ctwo = new Customer();
Cone.CustomerID = "100";
Cone.CustomerName = "abc";
Ctwo.CustomerID = "101";
Ctwo.CustomerName = "xyz";
List<Customer> lstCustomer = new List<Customer>();
lstCustomer.Add(Ctwo);
lstCustomer.Add(Cone);
JavaScriptSerializer jsonSerz = new JavaScriptSerializer();
string serializedData = jsonSerz.Serialize(lstCustomer);
return serializedData;
}
client side coding
<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="jquery.jqGrid.min.js"></script>
<script type="text/javascript">
function GetData() {
alert('Inside GetData');
var data = PageMethods.GetData(OnSuccess, OnFailed);
}
function OnFailed(error) {
alert('Failed');
alert(error.get_message());
}
function OnSuccess(data) {
alert(data);
}
$(document).ready(function() {
$('#submit').click(function() {
alert('Button Clicked');
$('#list').jqGrid({
url: 'http://localhost:1405/WebSite1/Default.aspx/GetData',
data: '{}', // For empty input data use "{}",
dataType: 'local',
type: 'POST',
contentType: "application/json; charset=utf-8",
colNames: ['CustomerID', 'CustomerName'],
colModel: [
{ name: 'CustomerID', index: 'CustomerID', width: 80,
align: 'left', editable: false },
{ name: 'CustomerName', index: 'CustomerName', width: 120,
align: 'left', editable: true}],
pager: $('#pager'),
rowNum: 5,
rowList: [10],
sortname: 'CustomerID',
sortorder: 'desc',
viewrecords: true,
width: 300
});
});
});
</script>
AND HTML code
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server">
</asp:ScriptManager>
<input type="button" id="submit" value="Fetch" title="Fetch"
onclick="javascript:GetData()" />
<table id="list">
</table>
<div id="pager">
</div>
First of all I recommend you to play a little with another working code which you can download here (see more information here). More links to another examples you can find here.
I try to describe some problems in your current code.
You use 'http://localhost:1405/WebSite1/Default.aspx/GetData' as the url. You shold better use only pathes like '/WebSite1/Default.aspx/GetData' or 'WebSite1/Default.aspx/GetData' or you can easy receive same origin policy problem.
You should use ASMX service instead of placing the code inside of ASPX page (Default.aspx/GetData). You should just add new item to your ASP.NET solution and choose Web Serice template. The corresponding code template will be added for you and web.config will be modified. In the same way you can place WCF service inside your ASP.NET project. The step is independ on the technology which you use (WebForms, ASP.NET MVC and so on).
Instead of manual JSON serialisation with respect of JavaScriptSerializer you should define [ScriptMethod(ResponseFormat = ResponseFormat.Json)] attriute to your method and return an object from the web method (like List<Customer> in your case). The JSON serialization will be done automatically for you.
You use dataType: 'local' which is wrong parameter for jqGrid. Correct parameter will be datatype:'json' (datatype instead of dataType and 'json' to make the request to the server).
Instead of type: 'POST' you should use mtype: 'POST'.
Instead of contentType: "application/json; charset=utf-8" you should use ajaxGridOptions: { contentType: "application/json" }.
The usage of data: '{}' is also wrong. Probably you try to use data parameter of jQuery.ajax like with dataType parameter. In jqGrid you should use pastData instead of data and the data parameter must be an array and has another meaning. I recommand you to look at the code of the example (see reference at the begin of my answer).
You should not place $('#list').jqGrid({...}); inside of click handle. The problem is that the code make some initializations of jqgrid and then fill the grid. What you probaly want is creating the grid only once and then refreshing it with another input data probaby (I am not sure that it is so). So you should move $('#list').jqGrid({...}); inside of $(document).ready(function() {...};. If needed you can use $('#list').trigger("reloadGrid") inside of the click event handle. Alternatively you can use GridUnload to destroy the existing grid before creating it new.
I can continue, but my main recommendation is to examine another examples and use ASMX or WCF service which provide the data for jqGrid.
Entire grid binding event is called before your page method.
You have put it under document.Ready event. Try calling it from the button click event.
I am not sure but there should be some way to bind json data to Jquery grid on client side without using the URL part.
try mapping "data:" to some Json value.

Why do I need to use .d to access data returned by jQuery AJAX?

I've put together some jQuery AJAX code using some tutorials I found on the internet. I'm new to jQuery and want to learn how to do things betters. I have a coworker who put together a beautiful web application using a lot of jQuery.
The thing I'm most confused about here is: why is it necessary to use the ".d" when referring to the response of my web method and what does it stand for?
// ASP.net C# code
[System.Web.Services.WebMethod]
public static string hello()
{
return ("howdy");
}
// Javascript code
function testMethod() {
$.ajax({
type: "POST",
url: "ViewNamesAndNumbers.aspx/hello",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg); // This doesn't display the response.
alert(msg.d); // This displays the response.
} // end success:
}) // end $.ajax
It was added in ASP.NET 3.5’s version of ASP.NET AJAX to prevent you from being vulnerable to this exploit: http://haacked.com/archive/2009/06/25/json-hijacking.aspx
(Answer sourced from http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/)
Microsoft does this to protect you from a security exploit. See the bottom of This Page for more information.
I guess alert(msg) displays "[object Object]" ?
If so it's because the object which is parsed through window.JSON (which happens under the hood when specifying json as dataType) does really look:
object = {
d: "some data"
}
Check what you are generating in ViewNamesAndNumbers.aspx/hello

Resources