Hi how can I pass a client side (JS) value in server side (C#)?
e.g.
I have a generated table (after uploading images) and it contains images and I want to select the image and throw the ID back in server side.
The uploade I used was JQuery Uploadify and I have a "onComplete" function
(simple code)
'onComplete': function (event, queueID, fileObj, response, data) {
$('#imgs').append('<img id="' + queueID + '" src="' + response + '" alt="' + response + '" />');
How can I do this?
To send a value from javascript to the server you have a couple of options:
Use AJAX if you want to stay on the current page
Redirect to a server side script and pass the value in the querystring
Let's consider the first case:
Assuming you have a web method capable of receiving the value on the server:
<%# Page Title="Home Page" Language="C#" AutoEventWireup="true" %>
<script type="text/C#" runat="server">
// Server side script in the code behind that will receive
// the value: The method needs to be static
// and decorated with the WebMethod attribute
[System.Web.Services.WebMethod]
public static string Foo(string id)
{
return "ok";
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head id="Head1" runat="server">
<title></title>
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
// Send an AJAX request to the server
$.ajax({
url: '/default.aspx/foo',
type: 'POST',
contentType: 'application/json; charset=utf-8',
// Pass the value as JSON string
// You might need to include json2.js for the JSON.stringify
// method: http://www.json.org/json2.js
data: JSON.stringify({ id: 'someId123' }),
success: function (result) {
// The result is also JSON
alert(result.d);
}
});
});
</script>
</head>
<body>
<form id="Form1" runat="server">
</form>
</body>
</html>
are you using Asp.net Forms? If so, you do understand the concept of Page Lifecycle and how it affects the state of the page?
I would suggest going javascript all the way in this one, please see jQuery + AJAX.
Related
Hi i have a question about Session variables, i want to call in GET via ajax, from my .aspx page, a page .asp that have VB6 code inside, i need to share Session variables between them actually i tried this:
ASPX file
<html>
<head>
<title>let's try Ajax</title>
<script type="text/javascript" src="Scripts/jquery-1.10.2.js"></script>
<script>
$(document).ready(function () {
var request = $.ajax({
url: "/Default.asp",
type: "GET",
dataType: "html",
cache: "false"
});
request.done(function(msg){
$("#insert").html(msg);
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
in the aspx: <%Response.Write(Session["try"].ToString()); %>
</div>
<div id="insert">
</div>
</form>
</body>
</html>
code behind page:
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
Session["try"] = "hello world";
}
}
finally .asp page
<%
[...]
Response.Write "" & Session("try")
Response.End
[...]
%>
Actually the Session doesn't show anything in the .asp page, but in the .aspx page shows it's string inside, what's wrong with my code? Is it possible to pass share a session?
I think, you want to share your session between Class ASP and ASP.Net. so you need to store
your session information in SQL server. Please refer below link
http://msdn.microsoft.com/en-us/library/aa479313.aspx
I have an application which has 80% of it's part in ASP.NET MVC 2.
I am using Anti-forgery token to avoid Cross-Site Request Forgery.
Say I have an action method -
public JsonResult AddMenuFavorite(int id) {
// code
}
which uses the token to prevent CSRF. I have various links in my MVC pages from there I can make a call to this action method smoothly without any error.
While making calls from classic ASP.NET pages, this shows error.
Reason:: Anti-forgery token is not embedded in ASP.NET pages it seems.
can any one help me with the solution?
In order to generate the required hidden field containing the token you could use the AntiForgery.GetHtml static method:
<%# Page Language="C#" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%= AntiForgery.GetHtml() %>
<asp:LinkButton
runat="server"
ID="btn"
PostBackUrl="~/SomeController/AddMenuFavorite/123"
Text="Go to the MVC site"
/>
</div>
</form>
</body>
</html>
And since your action returns JSON I suspect that you are calling it using an AJAX request. In this case you can use the value of the hidden field generated by the helper to send it along with the AJAX request:
$(function() {
$('#someLink').click(function() {
$.post(this.href, $('form').serialize(), function(result) {
// do something with the result
});
return false;
});
});
Here is the full code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
<style type="text/css">
#import "jquery.countdown.css";
</style>
<script type="text/javascript" src="Scripts/jquery.countdown.js"></script>
<script type="text/javascript">
$('#shortly').countdown({ until: shortly,
onExpiry: liftOff, layout: "{ps} seconds to go"
});
$(document).ready(function () {
shortly = new Date();
shortly.setSeconds(shortly.getSeconds() + 5.5);
$('#shortly').countdown('change', { until: shortly });
});
function liftOff() {
// refresh the page
window.location = window.location;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<span id="shortly"></span>
</form>
</body>
</html>
I've got the jquery.countdown.js in the Scriptsmap of visual studio. Also the stylesheet "jquery.countdown.css" is in the project.
Don't have a clue about what the problem could be. I'm kind of new to jquery and trying to learn it.
I'm not familiar with this countdown plugin, but, try moving the part
$('#shortly').countdown({ until: shortly,
onExpiry: liftOff, layout: "{ps} seconds to go"
});
into the function passed to $(document).ready, replacing $('#shortly').countdown('change', { until: shortly });
Because otherwise the shortly var is not initialized when you're trying to use it.
you have a error in liftOff function with windowwindow.location
function liftOff() {
// refresh the page
window.location = window.location;
}
I'm trying to set up a simple JQuery example in order to make AJAX calls to a .NET webservice. Using the following example below I'm getting AJAX errors that are just saying 0 in the result instead of any meaningful message:
Javascript Call
function QSHelloWorld() {
var options = {
type: "POST",
url: "http://localhost:1087/QueryService.asmx/HelloWorld",
data: "{}",
contentType: "application/json",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
};
$.ajax(options);
}
function AjaxSucceeded(result) {
alert(result.d);
}
function AjaxFailed(result) {
alert("Error: " + result.status + " " + result.statusText);
}
ASP .NET WebSite
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="jQueryTest._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script language="javascript" type="text/javascript" src="js/jquery-1.3.2-vsdoc2.js" />
<script language="javascript" type="text/javascript" src="js/qsAJAX.js" />
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="formMain" runat="server">
<div>
<script type="text/javascript">
QSHelloWorld();
</script>
</div>
</form>
</body>
</html>
ASP .NET WebService
using System.Web.Script.Services;
using System.Web.Services;
namespace QueryService
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class QueryService : WebService
{
[WebMethod]
[ScriptMethod]
public string HelloWorld()
{
return "Hello World";
}
}
}
When I make a call to the QSHelloWorld I get a messagebox saying Error: 0 with no further information.
I'm currently running this example using Windows 7, do I need to have anything specifically installed besides the .NET Framework 3.5 SP1 in order to get this to run properly?
Thanks,
Daven
Maybe this page will help you out. Their example uses JSON as well.
The issue is that the javascript files were loading file in Chrome, but not in IE. After making the following change in the ASP .NET Default.aspx file, everything seemed to work.
Changing:
<script language="javascript" type="text/javascript" src="js/jquery-1.3.2-vsdoc2.js" />
<script language="javascript" type="text/javascript" src="js/qsAJAX.js" />
to
<script type="text/javascript" language="javascript" src="/js/jquery-1.3.2-vsdoc2.js"></script>
<script type="text/javascript" language="javascript" src="/js/qsAJAX.js"/></script>
I've had problems when trying to load JQuery directly in the .ASPX page. Instead I have a ProjectBasePage class that in it's PageLoad does this:
Page.ClientScript.RegisterClientScriptInclude(typeof(ProjectBasePage),
"jQuery", ResolveUrl("~/js/jquery-1.3.2.min.js"));
It works for me...
I am trying to load mschart in my aspx page(SalesOverview.aspx) using jQuery.load() method,
I am loading another aspx page(ChartHandler.aspx) which accepts the parameters and render the chart .
but when trying to execute,the chart is not getting rendered sometimes.Instead i could see an image holder kind of thing in the page (Similar to what we see when we refer an invalid image url as an image tag src attribute value).
The code i am using is as below
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="SalesOverview.aspx.cs" Inherits="OmnexCRM_UI.SalesOverview" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head></head>
<body>
<form id="frmPag1" runat="server">
<div id="divGraph"> </div>
</form>
</body>
$(document).ready(function()
{
var startDate ="10/10/2009"
var endDate = "12/11/2009"
var height = "150";
var width = "730";
var strUrl = "ChartHandler.aspx?chartMode=salesOverview&startDate=" + startDate + "&endDate=" + endDate + "&height=" + height + "&width=" + width;
$("#divGraph").html("<div class='divLoadingProdReport'><img src='images/ajax-loader-gray.gif' alt='Loading...'/></div>").fadeIn(10, function() {
jQuery.ajax({
url: strUrl,
type: "POST",
processData: false,
contentType: "text/xml",
data: null,
success: function(data) {
$("#divGraph").fadeOut(200, function() {
$(this).html(data).fadeIn(100);
});
}
}); //ajax
});
});
In ChartHandler.aspx
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="pnlSalesChart" CssClass="pnlSalesChart" Visible="false" runat="server">
</asp:Panel>
</div>
</form>
In ChartHandler.aspx.cs,In page load,i am reading the querystring values and building an area chart and adding that to the panel.
Couple of things:
You're rendering a whole page to ajax, you should just render your panel
You are doing a POST to your ChartHandler page, this should be a GET
You're requesting text/xml, yet you aren't doing anything with xml
You're requesting a webpage. Just use a generic handler (ashx) for stuff like this
Example code
HTML page
<form id="form1" runat="server">
<div>
<p>Test page</p>
<div id="renderPanel">
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$.get("chart.ashx?propertyA=1&propertyB=2", function(data, textStatus) {
$("#renderPanel").html(data);
});
});
</script>
Create a generic handler (ashx) with the name 'Chart.ashx'
public class ChartHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
//process querystring, which is in 'context.Request.QueryString'
context.Response.ContentType = "text/html";
PlaceHolder wrapperPanel = new PlaceHolder();
//add your chart here
wrapperPanel.Controls.Add(
new Image() { ImageUrl = "http://www.geenstijl.nl/archives/images/niekijkenw.png" });
//render control to HTML
StringBuilder stringBuilder = new StringBuilder();
StringWriter stringWriter = new StringWriter(stringBuilder);
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
wrapperPanel.RenderControl(htmlWriter);
context.Response.Write(wrapperPanel);
}
public bool IsReusable {
get {
return false;
}
}
}
Add in web.config under httpHandlers:
<add verb="*" path="~/Chart.ashx" validate="false" type="ChartHandler"/>