Calling ASP method inside javascript code - c#

i wonder if there is any way to call an asp method that returns a string or something when you are in <script></script> tags.
Like this (it does not work):
<script language="javascript" type="text/javascript">
function isValid() {
var required = "<%= callAspMethodThatReturnsSomething() %>";
}
</script>
any help with this? thx!

There is no direct way to call c# method like in example above. But you can send $.ajax request to the server, or even send postback using _doPostBack(..,..)

The issue is that you are calling a method on the master page from the content page directly.
You can't do that - you need a reference to the strongly typed master page.
Try this (asp.net 4.0):
<%:((MasterPageClassName)Page.Master).callAspMethodThatReturnsSomething()%>
Or this (pre 4.0):
<%=((MasterPageClassName)Page.Master).callAspMethodThatReturnsSomething()%>

<% callAspMethodThatReturnsSomething() %>
this method in <% %> will work before what you want to do ,it may looks like does not work
yet,you can create a new button on page ,make it unvisible and use it's click event like document.getElementById("<%=button1.ClientID%>").click()

Related

pass parameter to one function in the code behind in C# from javascript

I am trying to pass parameter to one function in the code behind in C# from javascript
<script type="text/javascript">
$(document).ready(function () {
$("#some_id").click(function () {
var id = document.getElementById('HiddenField2');
var a = <%=btn_Click(id)%>;
});
});
</script>
<asp:HiddenField ID="HiddenField2" runat="server" Value='<%# DataBinder.Eval(Container.DataItem, "item_id")%>' />
code behind
public string btn_Click(String item_id)
{
/*do some thing*/
return null;
}
But this piece of code always giving me error of context. That id is not defined in this context.
Can some please let me know what wrong i am doing?
First, var id is javascript and the code within <%= %> is C#. You can't pass a variable between the languages like that.
Second, the value of id in this case is going to be a DOM element which C# can't use anyways. If you want to get the value of HiddenField2 within the code behind you can use HiddenField2.Value.
Third, since you're using ASP.net, instead of using jQuery's .click handler you should use the onServerClick attribute to wire up the button click behavior to btn_Click.
The button click event in C# will be triggered by Postback when your browser post data back to asp.net
I do not understand why you use HiddenField here,so my suggestion do not consider about it
Solution 1:
first you can extract your code in btn_Click to a HttpHandler(*.ashx in asp.net),then use Ajax by using js framework like jQuery to send data to your HttpHandler,data returned by HttpHandler can be processed by js
sample code is here
Solution 2:
if your code in btn_Click is relevent to your page, just use ajax Get method, the data will send to your page,the data returned by your data will be processed by js too
In the end, if you are new to web, I recommend you to learn or implement asp.net MVC, in my opinion, it is more flexible than asp.net webform

How to call javascript function from code-behind after ajax postback

I'm using Telerik controls in my project and I am using RadTabStrip for my purposes
<telerik:RadTabStrip ID="tsRequisitions" Skin="" MultiPageID="mpRequisitions" runat="server" Width="980" ScrollButtonsPosition="Right" ScrollChildren="True" OnTabCreated="tabCreated">
As you can see in this template I call tabCreated method every time when new tab has created. Now I want to call some javascript function from server-side(all mentioned is in RadAjaxPanel).
I've tried to use RegisterClientScriptBlock, but it didn't help me to fire my javascript function.
if (!ClientScript.IsClientScriptBlockRegistered("tabSelected"))
{
ClientScript.RegisterClientScriptBlock(this.GetType(),
"tabSelected", "TabSelected();", true);
}
And I have this in my .aspx file
<script type="text/javascript">
function TabSelected() {
console.log("dfgdfgfdg");
}
</script>
How can I call my function from code-behind after AJAX postback?
The following code snippet do the trick
RadScriptManager.RegisterStartupScript(this,this.GetType(), "tabSelectedScript", "TabSelected();", true);
RegisterStartupScript is static method of RadScriptManager class (I'm using Telerik controls here again, but maybe it will work with asp.net standart ScriptManager too).
Have you tried this ?
Page.RegisterStartupScript("OnLoad", "<script>TabSelected();</script>");

asp.net accessing javascript variables after ajax updatepanel

I'm using AJAX on an ASP.NET web project to update a page. Some of my functions return XML that I want to embed on the page after it reloads. This part works, here's a sample of how it looks at the top of the page:
var productXML = "<?xml version=\"1.0\"?><ArrayOfProduct xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><Product><ActualProdID>123</ActualProdID><Name>Test</Name><Description>Test</Description><Edition>Test</Edition><Platform>Test</Platform><Family>Test</Family><Type>Test</Type><DeploymentTypes>Test</DeploymentTypes><BaseActualProdID>Test</BaseActualProdID><Price>0</Price></Product></ArrayOfProduct>";
Later in the page I'm trying to use the XML but it's not working. I tried to do something simple and just throw an alert box in that looks like this:
<script type="text/javascript">
function closeLoading()
{
jQuery('.pleaseWaitPanel').css({ 'display': 'none', 'visibility': 'hidden' });
alert("here");
alert(productXML);
alert("here2");
}
</script>
closeLoading() is called inside:
window.onload = function () { Sys.WebForms.PageRequestManager.getInstance().add_endRequest(closeLoading); };
It loads the jQuery and the first alert "here" works perfect. When I go to alert the productXML, nothing happens. It doesn't throw a JavaScript error, I'm using Firebug. I can confirm the XML is on the page.
Any help on this would be GREATLY appreciated!!
From your code snippets, it looks like your closeLoading function is only being called in your window.onload function. This means that it won't be called after any Ajax request completes as the window won't be reloaded.
I would try moving your call to Sys.WebForms.PageRequestManager.getInstance().add_endRequest(closeLoading) to just before your closing server-side form tag:
<form runat="server">
...
<script>
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(closeLoading);
</script>
</form>
Hope this helps.
var productXML
Is a ServerSide variable, so you don't have access to this in Client script.
If you want to use in a javascript function you can do this :
1) Put the result in a textbox hidden, like
<input type='hidden' value='<%=productXML%>'>
then simply get the value of the textbox.

pass a c# variable to javascript function

I'm trying to pass a c# variable as an argument to a java-script function like
<%var count=model.SomeMode.Count();%>
when i pass it to my java script function "checkAll(count)" it does not fire but without the argument its workin fine
CheckAll
Remember the page gets created however you wish. So, you could do something like:
<script type="text/javascript">
var count = <%=model.SomeMode.Count(); %>;
</script>
You could apply the same logic in method calls, so you could do:
CheckAll
Javascript can't see your C# source directly - you need to write it into the Javascript source on the server side:
CheckAll
It should look like this:
<script type="text/javascript">
var count=<%=model.SomeMode.Count()%>;
</script>
Currently you're declaring your variable in C#, not outputting it in the page as a JavaScript one. Instead, you want to declare var count literally in the page and have it set to the output of model.SomeMode.Count().
This might be good for your solution:
<a href="#" onclick='return checkAll(<%=count%);'>CheckAll</a>
But there is an other way of doing this instead of conventional way:
Sharing Variables Between JavaScript and C# by Fredrik Kalseth

anchor text onclick to c# function

i have an iframe that which source need to be updated and refreshed. the way i want to do it is to click on an and with it's onclick function, i need to send something like myiframe.Attributes["src"] = "blah.aspx";
is there any quick way to do this?
thanks in advance
You can use javascript to send an AJAX query back to the server with the frame's source.
The javascript you could use is iframe.location.href where 'iframe' is the id attribute of your iframe.
Then you can send a callback to the server using ASP.NET AJAX (or another ajax call if you wish). Here is a good tutorial: http://ajax.net-tutorials.com/
You could do it all client side if you wanted to (untested code):
...
<body>
<a id="yourAnchorId">Load It</a>
<iframe id="youriFrameId" src="blank.html" width="500" height="400"></iframe>
<script type="text/javascript">
document.getElementById('yourAnchorId').onclick = function() {
var frame = document.getElementById('youriFrameId')
frame.src = "blah.aspx;"
frame.location.reload();
};
</script>
</body>
...

Categories

Resources