this is my scenario: I have an asp website that can merge tiff file. So, to do this i need to use a c# function and it is called after a javascript event.
The c# is like this:
public void mergeImages(string initialUrl, string lastImageUrl)
{....}
I created two hidden field like this:
<input type="hidden" id="hi1" value="D:\\ProvaUpload\\1.tif" />
to get the value to pass at the function, because I didn't know in which way I can pass js variable to it.
I call the function in this way:
'<%mergeImages(par1,par2); %>';
In which way can I pass variable value to the function?
Decorate the method with WebMethod Attribulte:
[WebMethod]
public void mergeImages(string initialUrl, string lastImageUrl)
{....}
Get the hidden fields, and pass these to Jquery Ajax call, from a button click
var hdn1 = $('#hi1').val();
var hdn2 = $('#hi2').val();
var parameters = '{initialUrl:' + hdn1 + ', lastImageUrl:' + hdn2 + '}';
$.ajax({
type: "POST",
url: "page.aspx/mergeImages",
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
}
});
Refer the stackoverflow thread.
ASP.NET - Passing JSON from jQuery to ASHX
This will help you to understand to use handler file (ashx) to do ajax json request.
your requirement can be achieved with this concept.
you do not need to call cs method into javascript. you should post using ajax on any kind of handler file e.g ashx, asmx, or any other service .
Nothing to do much you just need to take an extra button which will be hide in output:
<asp:button id="btnGetAndPassvalues" runat="server" Text="hide" Onclick="btnGetAndPassvalues_Click" Style="display:none"/>
Now javascript function should be like below:
<script>
$('[id$=btnUpload]').live('click', function (e) {
// code to finish Upload prosess
$('[id$=btnGetAndPassvalues]').click();
});
</script>
That's all and in click event get the values of hidden field:
protected void btnGetAndPassvalues(Object sender,EventArgs e){
string hd1=hiden1.Value;
string hd2=hiden2.Value;
}
or you can make AJAX Call,
one of the easy way to achieve this :-
As you already have two hidden fields but must add runat attribute to it ,so that
you can get their values at server side. Let's Say:-
<input type="hidden" id="hi1" value="D:\\ProvaUpload\\1.tif" runat="server" />
<input type="hidden" id="hi2" value="D:\\ProvaUpload\\2.tif" runat="server" />
and Make a hidden button :-
<asp:button id="btnhidden" runat="server" Text="hide" Onclick="btnhidden_Click" Style="display:none"/>
Now you can click the button in javascript function :-
function UploadFinished()
{
//your JS code:-
// After finish uploading ..Click the button .. i have used jquery for simplicity:-
$('input[id$="btnhidden"]').click();
}
Now in your code behind :-
protected void btnhidden_Click(Object sender,EventArgs e)
{
// you can get hidden fields values here ....
string val1=hi1.Value;
string val2=hi2.Value;
// Call your merge function here :-
mergeImages(val1,val2);
}
Related
I have a C# Web Forms application that is displaying a jqGrid on the home page. I struggled with the jqGrid for a while as it was returning the "jqGrid is not a function" error on any page that inherited from site.master.
To solve this, I put the code and script references for the grid in a user control and then referenced the control on the home page:
<%# Register TagPrefix="My" TagName="GridControl" Src="~/UserControls/Grid.ascx"%>
<My:GridControl ID ="gridControl" runat="server" />
Inside Grid.ascx I have the code to populate the grid which gets it's data from a stored procedure inside a handler:
<script type="text/javascript">
$(function () {
$("#dataGrid").jqGrid({
url: 'Handler1.ashx',
datatype: 'json',
I used the handler along with Newtonsoft JSON.NET to avoid the json string length error.
The stored procedure has 11 parameters which when set to NULL, return all rows, which is what I want for the initial page load.
sqlCmd.Parameters.Add("#ProjNum", SqlDbType.Int).Value = DBNull.Value;
So now, I want to filter the results based on values from dropdowns on Default.aspx. The dropdowns are populated from SQL calls as well. But my question is how to get the values from the dropdowns into my handler?
I know I can do something like url: Handler1.ashx?asgnID=19 where I've just hardcoded the value, and then get it from the context.Request.QueryString, but I still don't know how to pass the value.
I've also read about using session, and I've tried passing a json string in ajax from default.aspx in a java button click event - which didn't work because the handler ends up getting called twice. I'm a little green on this stuff, and was hoping for a better alternative.
In case anyone is having the same issue, I did the following to solve it:
Create a function to extract the parameter from the url.
function GetParameterValues(param) {
var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < url.length; i++) {
var urlparam = url[i].split('=');
if (urlparam[0] == param) {
return urlparam[1];
}
}
}
Assign the parameter value to a variable and use it in your Jqgrid url:
$(function () {
var id = GetParameterValues('id');
$('#statusGrid').jqGrid({
url: 'Handler2.ashx?id=' + id.toString(),
datatype: 'json',
mtype: 'POST',
colNames: ['Status', 'Status Date', 'Status Time',...
And, inside the handler, extract the id from the context in ProcessRequest()
int ProjNum = Convert.ToInt32(context.Request["Id"]);
I try to use PageMethod in asp.net.
First I add script Manager to my aspx page:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
I wrote onClick method on JS:
function TryAJAX() {
PageMethods.TryA( onSucess, onError);
function onSucess(result) {
alert('good.');
}
function onError(result) {
alert('Something wrong.');
}
}
and in the code behind:
[WebMethod]
public static String TryA()
{
return "JSON CHECK";
}
and I always get the message 'something wrong' . althouth that in debugger I see it's enter to the methood 'TryA'.
What is the problem?
thanks!!
i know this is not the exact path you were looking to take for a solution, but I think it is a WAY better option, so here's my 2 cents...
your button in html
<input type="button" id="myStupidButton" value="Click Me Yo" />
you javascript- I am going to use jQuery too , if that is really a problem I can give you a pure js option:
<script>
$(function(){
$(document).on('click', '#myStupidButton', function(){
$.ajax({
type: "POST",
url: "Mypage.aspx/TryA",
success: function(data){
// parse asp.net's response
data = $.parseJson(data);
//asp.net wraps all json into json like this "d" : "yourresponse"
alert(data.d);
}
});
});
I am having an javascript function for a HTML img click event in aspx page. And a server Method in its code behind page.Now I want to call the server method from the javascript function without any parameter only when the HTML img is clicked by the user.
C# Code Behind Method:
[WebMethod]
public void PopUpClick(object sender, EventArgs e)
{
//Something;
}
JavaScriptMethod:
$(document).ready(function () {
$('.clickme').click(function () {
PageMethods.PopUpClick();
});
});
Also I added into the master page: <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" EnablePageMethods="true" />
It is not working.When I debugging this Javascript function on the Chrome
I saw an error:Uncaught Reference Error:PageMethods is not defined.
.aspx
<div>
<p>Say bye-bey to Postbacks.</p>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<asp:TextBox ID="txtname" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="txtaddress" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnCreateAccount" runat="server" Text="Signup" OnClientClick="HandleIT(); return false;" />
</div>
JavaScript
<script type="text/javascript">
function HandleIT() {
var name = document.getElementById('<%=txtname.ClientID %>').value;
var address = document.getElementById('<%=txtaddress.ClientID %>').value;
PageMethods.ProcessIT(name, address, onSucess, onError);
function onSucess(result) {
alert(result);
}
function onError(result) {
alert('Something wrong.');
}
}
</script>
C#
[WebMethod]
public static string ProcessIT(string name, string address)
{
string result = "Welcome Mr. " + name + ". Your address is '" + address + "'.";
return result;
}
The WebMethods that are defined must be "static".
The following ajax call to a WebMethod "GetAllRegions" works fine, provided, the WebMethod is defined as static!!
$.ajax({
type: "POST",
url: 'GenerateEAInHtml.aspx/GetAllRegions',
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
});
The WebMethod is defined this way:
[WebMethod]
public static List<Region> GetAllRegions()
{
/* Your Code goes here */
return regions;
}
You might want to use this Ajax Post to also pass JSON data to the WebMethod by passing the data parameter!! This should help.
Assumption that your page name is abc.aspx and xyz is the function name that you have to call.
javascript :
function sendData(offset) {
$.ajax({
type: "POST",
url: "abc.aspx/xyz",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
}
Server Side : add Imports System.Web.Script.Serialization
WebMethod(enableSession:=True) _
Public Shared Function xyz() As String
your code here
End Function
Add module in web.config -> system.webServer
->system.webServer>
->modules>
->add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
->/modules>
->/system.webServer>
Back end C# code is separate from your front end JavaScript code. JS runs on the client side and C# runs server side. In order to have front end code fire off a back end functions, you would either need your function to do a form postback or use Ajax (or an equivalent) to call that pages function.
Try this
[WebMethod]
public static void PopUpClick(object sender, EventArgs e)
{
//Something;
}
Use an ImageButton. The handler does not need to be tagged as [WebMethod]
<asp:ImageButton runat="server" ID="btnPopUp" ImageUrl="img.png" OnClick="PopUpClick" />
Why do you want to use img directly?
There is a line at the top that says uncomment this to call it by JavaScript.
Uncomment that.
Then also add a [ScriptMethod] to your method like this:
[WebMethod]
[ScriptMethod]
public void PopUpClick(object sender, EventArgs e)
{
// Something;
}
You should then be able to call it from the PageMethods object.
However I've just done some research and it seems that you may need to place your code that uses PageMethods at the end / after the ScriptManager as its possible you are trying to use PageMethods before its been declared in the JavaScript. Alternatively if you're using jQuery then you can do it in the ready event so you know the page and everything has loaded. I think this will probably turn out to be the root cause.
A web method has to be declared as static and public.
Although you can't access the page directly, you can either pass what you need into the web method from the call in your client side code, or store what you need in session or a similar state storage mechanism that is accessible from your static web method.
That may require re-thinking what you're trying to do with it.
I am kind of new with jQuery and JavaScript, and I ran into a problem.
I am having some problems to open the jQuery UI Dialog Box from my ButtonField within the Gridview:
<asp:ButtonField ButtonType="link" Text="Modify Deadline" Visible="true" runat="server" CommandName="modifyDeadline" ControlStyle-CssClass="button" ItemStyle-CssClass="sliderPopupOpener"/>
At first I tried to give a class to the above and named it sliderPopupOpener, and make it open the jQuery Popup when clicked as below:
$(".sliderPopupOpener").click(function () {
$("#sliderPopup").dialog("open");
});
However, this was not working because of the postback, apart from that, it also does not work with my approach. Since I would like to get some data from the database before showing the jQuery UI Dialog. So I think the best approach is to call the Dialog function from the Code Behind.
How can I do this?
I tried this approach, but it did not work, I am not sure if I am doing something wrong.
if (e.CommandName == "modifyDeadline")
{
string sliderPopupFunction = #" <script type=""text/javascript"">
$(function () {
jQuery(function () {
$(""#sliderPopup"").dialog(""open"");
}
});
</script>";
ClientScript.RegisterStartupScript(typeof(Page), "key", sliderPopupFunction);
}
Is the above possible? If so, what am I doing wrong?
EDIT:
I noticed everyone is giving their answers with a way around this, rather than telling me whether this is possible just by calling the jQuery function from the Code Behind. Although I appreciate other solutions, I would appreciate if I could get this to work, with the least effort possible, through the code behind, since I have everything ready that way.
Instead of directly bind the click event handler, you should try delegated events using live (deprecated since jquery 1.7) or on.
That way, you should change this :
$(".sliderPopupOpener").click(function () {
$("#sliderPopup").dialog("open");
});
Into something like this :
$(body).on("click", ".sliderPopupOpener", function(){
$("#sliderPopup").dialog("open");
});
alternative
If the code-behind approach is more suitable for you, you should try calling the method directly in your script, i.e, change this :
string sliderPopupFunction = #" <script type=""text/javascript"">
$(function () {
jQuery(function () {
$(""#sliderPopup"").dialog(""open"");
}
});
</script>";
into simply this :
string sliderPopupFunction = #" <script type=""text/javascript"">
$(""#sliderPopup"").dialog(""open"");
</script>";
Also, if your sliderPopup is a server-side control, you should replace the #sliderPopup with the client Id generated by ASP .NET (using sliderPopup.ClientID).
Another thing to consider is if your sliderPopup located inside the update panel, you should try re-initialize the Jquery UI dialog first, something like this :
$("#sliderPopup").dialog().dialog("open");
Just Replace the <asp:ButtonField with <asp:TemplateField the write whatever you want:
<asp:TemplateField>
<ItemTemplate>
<input type="button" onclick='jsFunctionThatShowsTheDialog()'/>
</ItemTemplate>
</asp:TemplateField>
I think in this situation it would be better for you to use a plain old <input type="button/> button and use ajax to perform your call to the server, and then with the returned data append it to your html and use the dialog. Ajax will perform your code behind without posting back your entire page.
EDIT: here is an example I did a while ago
//declaring the web method annotation allows this method to be accessed by ajax calls
//scriptmethod tells this method to take the data that we're returning, and encode it as a json so we can use it in javascript
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<Person> getPeople() {
List<Person> people = null;
using (testDataEntities context = new testDataEntities()) {
people = context.People.ToList();
}
return people;
}
$(document).ready(function () {
$("#getPeople").click(function () {
$.ajax({
type: "POST",
data: {},
url: "Default.aspx/getPeople", //getPeople is the name of the method
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var data = msg.d;
var $table = $("<table></table>");
$.each(data,function(){
$table.append("<tr><td>"+this.MyProperty+"</td></tr>")
});
$table.dialog();
}
});
});
});
How would I raise an event if my html syntax is the following:
<select runat="server" id="selection" onclick="inputCheck" />
I tried this in the code behind:
protected void inputCheck(object sender, EventArgs e)
{
//doesnt matter because it raised an on click.
}
Exception:Microsoft JScript runtime error: 'inputCheck' is undefined
Here is an example with jQuery posting back to the server using ajax method, very clean and easy to use. Let me know if you have questions.
--HTML page
<select id="selection" name="selection" />
--Place this following code in the head tag in the html surrounded by the script tags; you must also include the latest jquery code (free download from http://www.jquery.com)
$(document).ready(function()
{
$("#selection").click(function()
{
var selectionValue = $(this).val();
$.ajax({
type: "POST",
url: "CodeBehindPage.aspx/WebMethodName",
data: "{'input':'" + selectionValue + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
//return value goes here if any
}
});
}
});
//Code behind page
[System.Web.Services.WebMethod]
public static bool WebMethodName(string input)
{
try
{
//do something here with the input
return (true);
}
catch(Exception ex)
{
throw ex;
}
}
--This will post the code to the server without any postbacks, which I like. In order to test, set a break point inside of the WebMethodName function and view the input passed in. HTH
The onclick in your first snippet runs only in javascript. To raise the event server-side, the first step is to build a javascript method for this event. From there, you have a few options:
You can build an ajax request to call a WebMethod
You can post the event back to the original page. Since you aren't using asp control, you will have to have code in your page_load to check the posted data for the event and raise it on your own.