Get the ASP.NET form name - asp.net

I'm looking for a way to get the name of the main HTML form so I can submit it from JavaScript.
The reason I can just set the name of the form is because the JavaScript is on a User Control that could get added to many different sites with different form names.
Thanks.

I'm not totally sure that this will address what you're asking for, so please comment on it:
In your script, when the User Control renders, you could have this placed in there. So long as script doesn't have a "runat" attribute, you should be good.
<script type="text/javascript">
var formname = '<%=this.Page.Form.Name %>';
</script>

I'm not sure , try "YourUserControl.Page.Form"
But why do you need the form name, are you going to have more than one form on your .aspx page , if not, you can get the whole post back JS code for the control that will do the post back (submit) using "Page.ClientScript.GetPostBackEventReference()" and use it to set the "OnClick" attribute of whatever you will use to submit the page.

you can't have more than one form control with runat="server" on an aspx page, so you cn use document.forms[0]

<script type="text/javascript">
var formname = '<%=this.Page.AppRelativeVirtualPath.Replace(this.Page.AppRelativeTemplateSourceDirectory,"")%>';
</script>

ASP.NET pages can only have one form, so its safe to just do:
document.forms[0].submit();

Related

Why javascript function not working from content page onload?

I am using ASP.NET 3.5.
I have a content page and I want to call a javascript function on this page's load event.
I tried adding:
onload="GetLocalDate();"
within the content page placeholder tag, but it is not working. But when I call this function from any button's OnClientClick event, it works.
How to make it work on Content Page's load event?
The content page "Placeholder" tag is a server side only control. It doesn't produce any code on the client other than arranging its contents etc. As such, the JavaScript onload handle is never rendered.
Examine your browser / client-side source to verify this.
Have you tried calling from document.ready?
$(document).ready(function () {
GetLocalDate();
}
Put that inside script tag on your page
<script type="text/javascript">
function pageLoad(){
GetLocalDate();
}
</script>
$(document).ready(function () {
GetLocalDate();
}
Should work. Since it was not working for you, I would assume that you do not have a reference to the jQuery library in your page.
If you don't want to include the jQuery library in your project for some reason, you could inject it from server-side code within your content page:
ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(...) <-- add necessary details here (the Type, scriptname, the text, and a Boolean to whether you need it to include its own tags)
You should also check to make sure it hasn't already been registered before using it though (IsStartupScriptRegistered).

__doPostBack outside of href causes full page postback

I have a custom control (ascx) which implements the IPostBackEventHandler interface for intercepting custom events triggered by custom rendered HTML links.
In this control I use an update panel and inside the update panel I use a literal control in which I render custom HTML links.
When I render the HTML links inside the literal control I use a StringBuilder with the following code:
sb.AppendFormat ("Text",
this.Page.ClientScript.GetPostBackClientHyperlink(this, custom_string_param));
Hyperlinks are rendered fine, and when clicking on them an asynchronous postback is triggered and a partial update is fired (since all links are rendered inside the Update panel).
The problem is that I need to do some custom Javascript before firing the __doPostBack which is rendered with the above code. So here is a simplified version of the changed code:
sb.AppendFormat ("Text",
custom_string_param);
Also in the ascx markup I use the following code (inside or outside the Update panel):
<script language="javascript" type="text/javascript">
function JSFunc(param) {
// custom js code here ....
__doPostBack('<%=this.ClientID%>', param);
}
</script>
The problem here is that when a link is clicked it performs a full postback and not a partial one. I also tested more simple versions of the above code and it seems that if you remove the __doPostBack from the href or the onclick events from the link ( tag) and move it to a custom js function which in turns you supply to the link, a full postback is triggered.
Note that there is no error on the page and in both cases the code work correctly. The page is rendering correctly depending on the parameters returned from the __doPostBack, but in the second case a full instead of partial postback is firing.
Any ideas?
Thanks in advance,
George
I think you can't call __doPostBack with the ClientID. It actually uses UniqueIDWithDollars, but generally with ASP.NET Web Forms I say: you don't want to know.
Since calling this method is all about abstracting away the details of how post back works, you would be better off asking the framework for the code. Luckily, there's a special method just for that, which will take care of the details. In your code it would look like something like this:
<script language="javascript" type="text/javascript">
function JSFunc(param) {
// custom js code here ....
<%= Page.ClientScript.GetPostBackEventReference(this, custom_string_param) %>
}
</script>
This let's the client script manager create the piece of JavaScript code, using a reference to your user control (this) and any custom event argument (custom_string_param).
There's one caveat though. When calling it this way, it will add javascript: to the beginning of the string.
To override this behaviour, you need to use an overload of GetPostBackEventReference that accepts an instance of PostBackOptions as its first argument, the instance having its RequiresJavaScriptProtocol property set to false.
PostBackOptions options = new PostBackOptions(this, custom_string_param)
options.RequiresJavaScriptProtocol = false;
Page.ClientScript.GetPostBackEventReference(options)

How to call javascript function from c#

I like to call a JavaScript function from c#. Can any one can give me code snippet.
More detail...
I have a asp.net page which has a asp button. when i click that button, i like to call javascript function.
like wise....
in my asp.net page,
<button id="save" onclick="i like to call a method resides in asp.net page'>Save</button>
More and more details...
when click the asp.net button, i like to perform some server side action and then like to call a javascript function from there itself...
For an asp:button you use OnClientClick
<asp:Button id="myid" runat="server" OnClientClick="alert('test')" />
On the assumption that you're coding in ASP.NET (including MVC), calling a JavaScript function would mean embedding the call in JavaScript into your ASPX code, like so:
<script type="text/javascript">
doSomething();
</script>
You do have the opportunity to pass information from your C# to the JS call, just as you would have any other code alter the results of your ASPX:
<script type="text/javascript">
doSomething("<%= GetSomeTextFromCSharp(); %>");
</script>
This is really stretching the definition of "calling JavaScript from C#" though. What you're doing is having your C#/ASPX code generate HTML/JavaScript, which the browser then interprets as it would any other HTML/JS (regardless of how it was generated).
Perhaps you could explain what you're trying to do a bit more.
i tried with this code it works for me check whether it helps
1)
Page.ClientScript.RegisterStartupScript(this.GetType(), "click", "alert('Informations');", true);
The other way is call the javascript method which is written in source page
Page.ClientScript.RegisterStartupScript(this.GetType(), "click", "xyz();", true);
You can't "call" a Javascript function from ASP.NET C# code-behind. You can write additional Javascript to the webpage. By the time the page is sent back to the user and the Javascript exists, your code-behind is gone. You can write out to a Literal or do a Response.Write()
Response.Write("<script language='javascript'>alert('Hellow World');</script>");
Sarathi, based on your recent update, it's not clear that you need any C# interaction at all. Your <button> appears to be strictly client-side (ie: HTML) with no ASP.NET interaction within it. To call your JavaScript function you'd attach the function call to the onclick attribute of the button tag:
<button id="save" onclick="mySaveFunction();'>Save</button>
Note that mySaveFunction() just needs to be defined in the browser's load stack for the current page. That means it could be defined in any of:
The ASPX page that holds the <button>
The Master page for the current ASPX page
One of the User controls (or MVC partials) loaded by the current ASPX page
An external JavaScript file that's loaded by one of the above.
Lastly, I'd just like to reiterate that there's nothing particularly C#/ASP.NET-specific about this. You could do the same with any language/framework, including static HTML files. Your question appears to be entirely JavaScript-dependent.
For the window object:
http://msdn.microsoft.com/en-us/library/ms536420%28VS.85%29.aspx
window.execScript
For the page pbject:
http://msdn.microsoft.com/en-us/library/dfbt9et1%28v=VS.71%29.aspx
RegisterClientScriptBlock
RegisterOnSubmitStatement
RegisterStartupScript
etc ...
you can call javascript function from code behind page ..for example you have closewindow function definition part in javasript..if you want to execute that function,you can write following codings in any click event in code behind page..
ClientScript.RegisterClientScriptBlock(GetType(), "close", "<script language=javascript>Closewindow();</script>", false);

jQuery and ASP.NET Control issue

If I have a custom ASP.NET control that renders as an html control with an ID, I'm trying to add an attribute to the input control with jQuery.
However, I'm running into some issues:
First, my jQuery is not able to select it.
I have so far:
$(document).ready(function() {
$(client id of the input control).attr('onclick', function () { alert('hey!'); });
});
It seems as if the jQuery is trying to find the input control but cannot.
Any ideas?
UPDATE:
Normally, the solutions presented would work but since this is a SharePoint Publishing .aspx page, Code blocks are not allowed... Trying other work arounds.
Just wire up the click event in jQuery.
$(document).ready(function() {
$(id of the input control)click(function() {
alert('hey!');
});
});
Also, make sure you aren't just putting the ID you typed in to the control in the jQuery. ASP.Net renders the control with a much different ID than you had given the control. On one of the sites I run, I have the following button:
<asp:Button ID="btnSignup" runat="server" Text="Sign Up" />
The ID in the rendered HTML is not btnSignup, it actually renders as ctl00_cpLeft_btnSignup. To select that control with jQuery, you can do this:
$("input[id$='btnSignup'").click(function() { ... });
Edit:
$("input[id$='btnSignup'}").click(function() { ... });
You can also select using:
$("#<%= btnSignup.ClientID %>").click(function() { ... });
Edit:
I looked into using the <%= ... %> method and you would have to have your javascript IN the ASPX/ASCX file itself for it to work. Because of this, I'd stick with the regex method.
What do you use as the ID of the input control?
You have to use the ClientID of the control, not it's ID.
You need to use its ClientID. If your ASP.NET markup looks like this:
<uc:MyControl runat="server" ID="myControl1" />
Your jQuery selector should look like this:
$(document).ready(function() {
$("<%=myControl1.ClientID%>").attr('onclick', function () { alert('hey!'); });
});
Selecting a ASP.NET generated ID with jQuery
Is your ASP.NET control in a master page or a user control? ASP.NET will prepend a bunch of identifiers to your ID to make sure it is unique.
What is the ID of the control coming out as in HTML?
If you're setting the ID of the rendered HTML control to the ID given to the ASP.NET control, you need to be aware of how ASP.NET handles control ID namespaces. Essentially, each control nested within a control needs to always guarantee a unique identifier. ASP.NET maintains this by taking the ID assigned to a control and prepending it with the ID of every control that contains the control. Thus, a control on a page will contain a string of ids going up to the form on the page itself.
You do not want to have to re-construct this client-side. Instead, Control defines ClientID, which will return the ID of the control as rendered on the client. Embed this into your jQuery, or into a javascript variable that your jQuery can see if you are putting the jQuery in a separate script file) and you should be fine.
just to inform you, the document.ready part is not needed, using asp.net control the id is changed to something different then what is expect, a ct100.... is thrown on the beginning of it, so this way will look for the actual id name even though asp.net throws the mangled code on the beginning,because it looks for all elements (*) that have an ID that ends with the specified text.
$(function() {
$("*[id$='idofcontrol']".click(function() { alert('hey!'); });
});
or go to the view source and copy the id name and paste it in your code or just use the css class selector as so:
$(function() {
$('.myclassname').click(function() { alert('hey!'); });
});
Since you mentioned Sharepoint you might be interested in this series on EndUserSharepoint that focuses on integrating jQuery with Sharepoint. The author discusses getting jQuery to manipulate the webparts.

JQuery output a dynamic control in a div

How do I handle the click of a checkbox to show another control preferrably a user conrtrol (ASP.NET ) dynamically.
I don't know anything about the system you're using but the low down dirty way I'd do this is...
Stick the user control on a blank page of it's own.
When the checkbox is clicked, have JQuery go get the HTML content of the page the user control is on and stick it in the div.
This will result in not-so-neat html in the calling page though.
And is this an asp:CheckBox or an html input?
If you want to create a new object, you can do this:
var checkbox = $("<input type='checkbox' ... />");
$('div#someID').append(checkbox);
Though it sounds like you perhaps want to get the data to append from an AJAX call. I can't quite tell from the question.
Assuming you hide the control with CSS by default you could shorten TStamper's code to something like:
$(function() {
$('#checkbox').click(function() {
$('#control').toggle();
});
});
<mycontrol:UC id="control" runat="server" />
I'm partial to using jquery's taconite plugin. It enables you to return multiple controls from a single ajax call.
For a simple show/hide control scenario rendering a hidden control on a page is good enough. If your control is big or changes due to user actions then your best bet is rendering control on the server and using js to update DOM.
If you're using jquery for your DOM updates and wish to find control by id use:
$("[id$=controlId]")
This will locate your control even with asp.net prefixes to the id.
I'm working on a simple c# wrapper for the taconite plugin which should enable you to use the plugin more easily (sample web site coming soon).
Are you looking for something like this:
$(function(){
$('#Control').hide(); //initially hide the control
$('#checkbox').click(function(){ // bind the checkbox click event
if ($('#checkbox').attr('checked')) {
$('#Control').show();
}
});
});
<mycontrol:UC id="Control" runat="server" />

Resources