I need to use the javascript functions to show and hide an element on my page, but calling it from within a C# method. Is this possible?
EDIT : I tried RegisterStartupScript (see below) but this did not hide the elements as I had hoped :
HidePopup("CompanyHQSetup", "$('#<%=DivDataProvider.ClientID %>').hide();$('#<%=modalOverlay.ClientID %>').hide();");
private void HidePopup(string Key, string jscript)
{
string str = "";
str += "<script language='javascript'>";
str += jscript;
str += "</script>";
RegisterStartupScript(Key, jscript);
}
EDIT : Got around this by using a hidden field boolean to determine whether or not to hide or show the elements
Yes, check out RegisterClientScriptBlock.
Here's a snippet taken from that link:
public void Page_Load(Object sender, EventArgs e)
{
// Define the name and type of the client script on the page.
String csName = "ButtonClickScript";
Type csType = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the client script is already registered.
if (!cs.IsClientScriptBlockRegistered(csType, csName))
{
StringBuilder csText = new StringBuilder();
csText.Append("<script type=\"text/javascript\"> function DoClick() {");
csText.Append("Form1.Message.value='Text from client script.'} </");
csText.Append("script>");
cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
}
}
One is server side, the other is client side. They can pass variables to each other (Javascript to ASP would be via forms/querystring/cookies and ASP to JS done via response.writing variables), but they can't directly interact.
you can use page.RegisterClientScript method to do that go on the following url
http://msdn.microsoft.com/en-us/library/system.web.ui.page.registerclientscriptblock.aspx
and give it a try
Javascript is client side, c# is server side. You can't call javascript directly from C#. Take a look at Comet though, it will show you how you can push data from the HTTP server to the webpage.
Related
I need a code segment to call a javascript function recordInserted() which shows up an alert, from my following code behind method,
protected void add_Click(object sender, EventArgs e)
{
String gradename = txt_gradename.Text;
int allocatedclasses = Int32.Parse(txt_allocatedclasses.Text);
String headid = txt_head_id.Text;
int numberofstudents = Int32.Parse(txt_numberofstudents.Text);
db = new DBConnection();
db.getConnection();
db.executeUpdateQuery("INSERT INTO Grade (GradeName,AllocatedClasses,GradeHeadID,NumberOfStudents) VALUES ('"+gradename+"','"+allocatedclasses+"','"+headid+"','"+numberofstudents+"')");
//I Need to call it from here before redirecting
Response.Redirect("AdminReferenceGradeAdd.aspx");
}
Please helpp me with this.
I have tried the following but never worked,
Page.ClientScript.RegisterStartupScript(this.GetType(),"Call my function","recordInserted()",true);
This will never work .. beacuse you are saying to redirect.
when you say Response.Redirect every thing which you have prepared to send is not sent,instead response is redirect to a new page.So your client script never reaches to browser.
you can use it like this :-
Page.ClientScript.RegisterStartupScript(this.GetType(),"Call my function","recordInserted();window.location.href='wwW.google.com'",true);
use window.location.href to redirect to your page("yourpage.aspx').
Try this:
ClientScript.RegisterClientScriptBlock(typeof(Page), "Call your function", "recordInserted()", true);
Or try calling Javascript function after a second:
ClientScript.RegisterClientScriptBlock(typeof(Page), "Call your function", "setTimeout('recordInserted()', 1000)", true);
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById('directions_panel');
summaryPanel.innerHTML = '';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + '</b><br>';
summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
}
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
my button event is not fired...i want to shows the get directions using two dropdown list controls using server side controls but my button event is not fired ...wht i do?
<asp:Button ID="btnsubmit" runat="server" OnClientClick="return calcRoute();" Text="Submit" />
how to cal javascript method into serverside...please tell me..
Why have you got a server side button in the first place?
The button doesn't call a submit event, nor does it post back to the server. So why not simply use a normal html button?
Even your Javascript function doesn't return a true or a false so using return calcRoute() will always return a false event.
In any case, try using the normal onClick event rather than OnClientClick.
edit
Seems to me a lot of what you are doing here could be solved using jQuery in a much better way than you are trying to do here.
Syntax :
public void RegisterClientScriptBlock(
Type type,
string key,
string script,
bool addScriptTags
)
Parameters
type
Type: System.Type
The type of the client script to register.
key
Type: System.String
The key of the client script to register.
script
Type: System.String
The client script literal to register.
addScriptTags
Type: System.Boolean
A Boolean value indicating whether to add script tags.
public void Page_Load(Object sender, EventArgs e)
{
// Define the name and type of the client scripts on the page.
String csname1 = "PopupScript";
String csname2 = "ButtonClickScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
String cstext1 = "alert('Hello World');";
cs.RegisterStartupScript(cstype, csname1, cstext1, true);
}
// Check to see if the client script is already registered.
if (!cs.IsClientScriptBlockRegistered(cstype, csname2))
{
StringBuilder cstext2 = new StringBuilder();
cstext2.Append("<script type=\"text/javascript\"> function DoClick() {");
cstext2.Append("Form1.Message.value='Text from client script.'} </");
cstext2.Append("script>");
cs.RegisterClientScriptBlock(cstype, csname2, cstext2.ToString(), false);
}
}
I am not add "return" false condition...My Button is getting a PostBack right now, that could be a problem. So add
Return false;
condition..
Then it will be working fine...thanks for the response..
So, I am dynamically generating jQuery using C# and sending it to the webpage.
The problem is it appears to be generating correct jQuery according to the file and according to Js Fiddle but it does not actually work on the page.
The jsFiddle is here http://jsfiddle.net/ER2hE/
Now I looked up how to send javacript to the website. It should work like this.
http://msdn.microsoft.com/en-us/library/bb359558.aspx
and my code which does that is this method
private void sendScript(string script)
{
const string someScript = "alertMe";
//send the built script to the website.
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), someScript, script, true);
}
This is super simple it has worked for other pieces of code calling. But it has not for this instance.
The code that calls it is this in my C#
private void populateGroups()
{
//this generates correct javascript according to the file and JS fiddle but unfortunately doees not work.
string splitme = "USE ACES SELECT GroupName, GroupID FROM PrimaryGroup ORDER BY GroupName";
DataTable dt = fillDataTable(splitme);
string script = "";
foreach (DataRow dr in dt.Rows)
{
//add the locations to the <select> box
script += " $('#groupList').append('<option value=\" " + dr.ItemArray[1].ToString() + " \"> " + dr.ItemArray[0].ToString() + " </option>'); ";
}
sendScript(script);
JSErrorLog(script, "GROUPS");
}
The whole thing is being called on startup
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack == false)
{
populateMakes();
populateLocation();
populateGroups();
}
}
The jQuery its generating also works in JSFiddle I am pulling this from a method that writes the javascript it generates in a method calling here is the fiddle JSErrorLog.
http://jsfiddle.net/ER2hE/
Oh and my html in my aspx file looks like this
<div class="row2">
<span>Group</span>
<select id="groupList" multiple="multiple" onclick="setGroups()" class="normalsize">
</select>
</div>
I believe that is everything. I just want my stuff to work. I am willing to post any additional code, just ask. If you have an idea as to why its not working, let me know.
When does it actually execute that code? Before or after the element with id "groupList" exists in the DOM? My guess is before.
Solution? Wrap your code inside a document.ready handler.
jQuery(function($) {
$('#groupList').append('<option value=" 46 "> AC Units </option>');
// etc etc
});
Return simple string js code. And run it with eval()
I have this C# code in my class:
private static void error_message(Sybase.Data.AseClient.AseException salah)
{
Page executingPage = HttpContext.Current.Handler as Page;
Type cstype = HttpContext.Current.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = executingPage.ClientScript;
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, "PopupScript"))
{
String cstext = "alert('" + salah.Message + "');";
cs.RegisterStartupScript(cstype, "PopupScript", cstext, true);
}
}
which produce this code
<script type="text/javascript">
//<![CDATA[
alert('ua_services not found. Specify owner.objectname or use sp_help to check whether the object exists (sp_help may produce lots of output).
');//]]>
</script>
But the alert box doesn't show up, and Chrome logs an error "Uncaught SyntaxError: Unexpected token ILLEGAL "
What's wrong with my code?
Your salah.Message contains a CRLF. Trim it or escape it.
Or wrap RegisterStartupScript in a method that does it.
I am developing an online listen music website, on that I want to play song based on the user selection from gridview.right now I am using flash object for playing mp3 and video file this is running fine but its static path.how I can dynamically pass file URL of selected song on flash object.
waiting for your reply.
Using flashvars (requires reloading the page/SWF)
The easiest way would be to pass in the URL as a flashvar, e.g. via the querystring of the SWF file in your object/embed tag:
MyPlayer.swf?url=/path/to/song.mp3
The /path/to/song.mp3 can of course be printed by some server-side logic.
In Flash, you can then access the value of this variable using the LoaderInfo instance of the root:
var url : String = root.loaderInfo.parameters['url'];
If you want to provide a default for when no flashvar is specified, which is great for dev purposes especially, you can do this by using the || operator.
var url : String = root.loaderInfo.parameters['url'] || 'default.mp3';
This will use the specified URL if such exists, or else fall back to use default.mp3.
Using ExternalInterface & Javascript
If you don't want to reload the page, set up a javascript interface to your Flash player using ExternalInterface, e.g. like so:
if (ExternalInterface.available) {
ExternalInterface.addCallback('playUrl', playUrl);
}
function playUrl(url : String) : void {
// TODO: Add playback code here, e.g. using new Sound(url);
}
Then, from Javascript, you can do this:
var swf = document.getElementById('idOfSwfEmbed');
swf.playUrl('http://example.com/path/to/song.mp3');
This will invoke the ActionScript method playUrl() using the javascript API that was set up by ExternalInterface.addCallback().
I don't know .NET, so you'll need to figure out yourself how to invoke the playUrl() javascript method when a song is selected in your GridView.
If you use the <object /> tag to add the *.swf to the page:
Add following to the tag:
<object ...>
<param name="flashvars" value="path=<%# YOUR_PATH; %>">
</object>
And then inside the SWF:
var path:String = root.loaderInfo.parameters.path;
Hello friends i have got the answer for dynamically play the song.here is my code for this.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Play Now"))
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gridCalls.Rows[index];
string songname = row.Cells[5].Text; // second column in the sql server database
StringBuilder str = new StringBuilder();
str.Append("<object width='300px' height='300px'>");
str.Append("<param name='autostart' value='true'>");
str.Append("<param name='src' value='songs/" + songname + "'>");
str.Append("<param name='autoplay' value='true'>");
str.Append("<param name='controller' value='true'>");
str.Append("<embed width='300px' height='300px' src='songs/" + songname + "' controller='true' autoplay='true' autostart='True' type='audio/wav' />");
str.Append("</object>");
LoadPlayer.Text = str.ToString();//here loadplayer is label control
}
}