Trigger jquery function from c# codebehind - c#

I'm fairly new to asp.net/c# and very new to jQuery so please forgive me if this is a newb question.
I have a jQuery fancybox installed which is defined by:
function pageLoad(sender, args) {
$("#ctl00_wpm_ShowProduct_ctl04_TestAddToCart").fancybox({
'width' : 600,
'height' : 620,
'type' : 'iframe' });
}
When I click the asp:HyperLink that renders as ctl00_wpn_ShowProduct_ctl04_TestAddToCart everything works (I realize if I move things on the page this could break but I need to make it work before I make it work well).
I have another asp:Button on that page that I want to do some processing and then open the target URL (calendar) in a fancybox. In the original the click on the link brought fancybox into play and opened the calendar URL. Now if I remove that, how do I get the same results from the button after it does its half-dozen other tasks? I won't have a link to which I can tie the jQuery activation.
I know that codebehind is server and jQuery is client, but if it can work from a link it should work from a button.

I would recommend using ClientID on the client side.
If you can do it exclusively through the front end, you could do something like this.
<asp:Button OnClientClick="LaunchTheFancyBox()" ID=""... />
<script>
function LaunchTheFancyBox(){
$('#<%=myControl.ClientID%>').fancybox({
'width' : 600,
'height' : 620,
'type' : 'iframe'
});
}
</script>
Note: If you need to send it from the server, you need to inject it through an control.
Here's a post with the same sort of question
http://www.eggheadcafe.com/community/csharp/2/10346901/open-jquery-fancybox-from-codebehind.aspx

If you want to run javascript on postback and:
you are using AJAX you can do this:
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ScriptKey", "myFunction();", true);
otherwise you can use this:
ClientScriptManager.RegisterClientScriptBlock(this.GetType(), "ButtonClickScript", "myFunction();", true);
References:
http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.registerstartupscript.aspx
http://msdn.microsoft.com/en-us/library/z9h4dk8y.aspx

In your button, use (you'll need to set your parameter values):
OnClientClick="pageLoad(sender, args)"
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick.aspx

Related

ConfirmButtonExtender doesn't cancel

I inserted this confirm button extender into my webpage. I have 2 option that is ok and cancel. When i clicked okay, it updates my database. But when i clicked cancel and also updates my database.
<asp:ConfirmButtonExtender ID="btnClear_ConfirmButtonExtender" runat="server" TargetControlID="btnClear"
ConfirmText="Are you sure you would like to update the following police report? The page will automatically refreshes if the report has been updated successfully"
OnClientCancel="CancelClick" />
I didnt enter any codes in my back-end side. So i guess the problem lies with the source code.
Source Link : ConfirmButtonExtender
Try to remove the OnClientCancel="CancelClick" and add Enabled="true".
It should work.
I believe OnClientCancel specifies a javascript function to call not server side method. Instead of the code you have for CancelClick, use this as a test in your HTML markup to see it in action:
<script type="text/javascript">
function CancelClick()
{
alert('called by javascript');
}
</script>
Now check that cancel button is still Updating or will show you the called by javascript message on alert.
Hope it clear and works for you.

how to call a javascript function from codebehind in asp.net

protected void addSchoolButtonClick(object sender, ImageClickEventArgs e)
{
Page.ClientScript.RegisterStartupScript(GetType(), "MyKey1", "SchoolSearchPopUp();", true);
/*Some code*/
}
I am developing a website in asp.net.At a Hyperlink onclick event i want to call a javascript function"SchoolSearchPopUp()".this function is for creating a new popup window and it is working correctly.But my problem is ,a javascript function is calling or pop window opens only after executing the rest of the code in that function and that code need's some data that occurs as a result of popup.How can i create the popup before executing the rest of code in that function.
Change your postback trigger to something within the popup.
I don't think javascript can be called from code behind. C# is running from the server and java is all client side. There's a good explanation to a similar question here: http://forums.asp.net/t/1117189.aspx
If you need to execute a javascript function, you could try changing the hyperlink to a button and making use of the OnClientClick property. This executes script client side rather than calling a method on the server.
<asp:button id="Button1"
text="Click Here"
onclientclick="SchoolSearchPopUp()"
runat="server" />
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick.aspx
You will need to write JavaScript on the page to handle the click of the button first and then call to the page method on the server.
Add an OnClientClick attribute to your button element and run your JavaScript method from there:
<asp:Button ID="TestButton" OnClientClick="SchoolSearchPopup()" Text="Click Me" OnClick="addSchoolButtonClick" runat="server"/>
<script type="text/javascript">
function SchoolSearchPopup()
{
alert("Popup");
}
</script>
If you want to execute some javascript before your postback you will need to register your hyperlink's click event to a js method, then submit your post to the server after performing whatever client side logic you are looking to run. (not the other way around, using RegisterStartupScript)
Example:
$("#myHyperLink").click(function() {
// do page logic, in your case show a modal window
$("#myModalDivContainer").show();
// submit your post to the server... replace targetClientID with ID of server control you're posting to
__doPostBack('targetClientID', '');
// NOTE: If you want to perform an AJAX request instead simply use some jQuery here instead. it's up to you how to handle the request from this point :)
});
Hope this helps!

How can I use a Modal Pop Up control in ASP.NET similar to a WinForms Message box?

I am building a form, where required field validation must have been checked. I am not using asp validator. I am using JQuery validator like
function checkRequiredInputs(){
$("#frmSaleSubmissionInfo").validate({
rules:{
txtFName:{required: true},
txtLName:{required: true},
txtAddress:{required: true},
txtPhone:{required: true}
},
messages:{
txtFName:"Enter Name",
txtLName:"Enter Name",
txtAddress:"Enter Address",
txtPhone:"Enter Phone Number"
}
});
This is my client side validation. I am using c# in my code behind page. Now if I turned off allowjavascript option in my browser, as far as I know it won't allow javascript. So I am also doing server-side validation for required field. But, since ASP.NET does not have a message-box control, I am having trouble to let the user know what field he is keeping empty. Is there any way to use a control like the message box to show or let the user know what field(s) is/are required to fill the form successfully?
In my point of view, the best fitted to your requirement is using ASP.NET AJAX Toolkit ValidatorCallout control, which can help you to build such solution more fast way.
But if you don't want mixed up two javascript framework (ASP.NET AJAX and jQuery) than you can be expired here, where you can find a solution how to deal with a validation and jQuery.
If you want a modal popup, just send some javascript from the server code:
Response.Write(
"<script type='text/javascript'>alert('A required field is missing.');</script>");
alert() is a javascript function. Response.Write() adds the <script> element to the end of the HTTP response (i.e., the rendered HTML page).
A more elegant approach would be to use the ClientScriptManager to register a startup script:
protected void Page_Load(object sender, EventArgs e) {
this.ClientScript.RegisterClientScriptBlock(this.GetType(),
"RequiredFieldValidationScript",
"alert('A required field is missing.');",
true);
}
The javascript code alert('A required field is missing.'); will be executed after the postback.
See also: https://web.archive.org/web/20210417085026/https://www.4guysfromrolla.com/articles/021104-1.2.aspx
Without javascript, I can't imagine a simple way of recreating a modal type popup. You would have to go as to postback and re-render the page with a DIV blocking out the page and another div on top of it with the errors.
You can always pipe out the errors to a tag next to the submit button and call it a day though.

hyper link to set drop downlist to visible

Wondering if there is a way upon clicking on a hyper link to set drop downlist to visible in code behind or asp?
<asp:HyperLink ID="HyperLink2" runat="server">View More Workout Programs ยป</asp:HyperLink>
If you have to do it in code-behind, then use a LinkButton instead of a HyperLink. Then it will have a click event just like any button and in that click event you can set the other element to .Visible=true.
However, does this need to be done in code-behind? Keep in mind the difference in "visibility" between server-side and client-side code:
If set to .Visible=false on the server-side, the content is not delivered to the client at all.
If set to display:none on the client-side, the content is present and can be viewed in the page source, it's just not displayed by the browser.
In some cases, the former is needed for security purposes. But if it's just a matter of user experience then I would recommend showing/hiding the content entirely on the client-side so as to avoid post-backs that do nothing more than change element display properties.
For example (assuming jQuery):
<a id="toggler" href="#">Show the content</a>
<div id="hidden" style="display:none;">Content</div>
<script>
$(document).ready(function(){
$("#toggler").click(function(){
$("#hidden").show();
});
});
</script>
Use an asp:LinkButton instead of a hyperlink and handle the OnClick event. In the OnClick event, toggle myDropDownList.Visible depending on whether you want to show it or not.
You should implement that kind of feature in the client (javascript code) to improve user experience.
Anyway, you can use a Panel with Visibility=false and put Visibility=true in code behind when link is clicked. You would need to adjust the position of that panel with css to look like a dropdown.
You can try with JQuery : http://www.jquery.com
It will be something like
<script type="text/javascript">
$(document).ready(function(){
$("#<% =HyperLink2.ClientID %>").click(function() {
$("#<% =DropDownList1.ClientID %>").toggle();
});
});
</script>
If you need to send form back to the server, use asp:LinkButton instead and handle OnClick event on the server side. If you need to show drop down list on the client side, use javascript function with onclick client event to show or hide any section you want.

JQuery Facebox Plugin : Get it inside the form tag

I am wanting to use the Facebox plugin for JQuery but am having a few issues getting it running how I want. The div that houses the facebox content is created outside of the tag so even though I am loading up some web controls none of them are firing back to the server.
Has anyone dealt with this that can give me some pointers?
poking around the facebox.js I came across this line in the function init(settings)...
$('body').append($.facebox.settings.faceboxHtml)
I changed that to ...
$('#aspnetForm').append($.facebox.settings.faceboxHtml)
and it loads up in the form tag, not sure yet if there are any side effects
You can use this code to register the PostBack event:
btn.OnClientClick = string.Format("{0}; $.facebox.close();",ClientScript.GetPostBackEventReference(btn, null));
this will let the button fires a PostBack.
Even after the :
$('#aspnetForm').append($.facebox.settings.faceboxHtml)
change I found it problematic. When you look at the page source using firebug you see that all the html in the div assigned to be the facebox div is doubled up (repeated).
So all of those controls with supposed unique id's are doubled up on the page, that can't be good on the postback, i've decided putting asp.net web controls in a facebox is not a good idea.
I modified facbox.js to do this. Maybe there is a better solution but this works like a charm
Here what i did:
add two lines on top of facbox.js before '(function($)'
var willremove = '';
var willremovehtml = '';
find "reveal: function(data, klass) {" and add this lines before the first line of function.
willremove = data.attr('id')
willremovehtml = $('#'+willremove).html()
$('#'+willremove).html('')
find "close: function() {" and make it look like below.
close: function() {
$(document).trigger('close.facebox')
$('#'+willremove).html(willremovehtml)
willremovehtml = ''
willremove = ''
return false
}

Categories