jquery used only on codebehind boolean = true - c#

I have a modal popup div that displays when a textbox is clicked. However, I only want this functionality if the user has permissions to this feature, otherwise I want to completely ignore all code associated with the textbox being clicked (ie. the user will just type values into the textbox). How can I set the JQuery code for textbox click, to only happen based on a boolean variable retrieved in the codebehind from the database?

You can warp the script with a literal control, and open/close it if have permissions as:
<asp:Literal runat="server" id="MoreScript" EnableViewState="false">
<script>
functions MoreToDo(){
}
</script>
</asp:Literal>
and on code behind you just set the MoreScript.Visible according to your permissions. I select the Literal because you can add it on the header and is not leave any marks, and also you can direct see the javascript code on page.

I would do something like this probably
<script>
if ("<%= CodeBehindProperty %>" == "true")
{
//Attach click events
}
</script>

You could try to register the jQuery function from codebehind by useing RegisterStartupScript method.
public void Page_Load(Object sender, EventArgs e)
{
String scriptString = #"<script type='text/javascript'>
$(document).ready(function($){
$('#Element').click(function(){
//open popup
});
}
</script>";
if(hasPermission())
this.RegisterStartupScript("PopUpScript", scriptString);
}

Related

Is it possible to set an HTML button as default inside a form?

I'm working on a asp.net page and I have several buttons in my page, some of them are asp.net buttons, other are HTML input[type=button] elements. HTML buttons are used to make AJAX calls.
When the user press ENTER I need to set as default button one of these HTML buttons, but at the moment the first button in the page is trigged.
Is there a way to set a plain HTML button as default on my form?
Try this :
// JavaScript Code
var body = document.getElementsByTagName('body')[0];
body.onkeydown = function (e) {
if (e.keyCode === 13) { //enter key code
// call your html button onclick code here
}
}
I'm using JQuery, so I modified the code in the Mohit Pandey answer:
$("body").keypress(function (event) {
if (event.which == 13) {
event.preventDefault();
// my function
}
});
read this article
http://www.codeproject.com/Articles/35180/How-To-set-Default-Button-for-ENTER-key-pressed-ev
you can use it in somewhat this way
<form id="form1" runat="server" defaultbutton="Button1" >
Can you not put the form inside a panel and use the defaultbutton property
<asp:Panel runat="server" DefaultButton="btnSomething">
...
</asp:Panel>

How to load javascript function from an dynamicall added control?

The Master page got a ScriptManager.
Then i got a Control with a ScriptManagerProxy and an UpdatePanel.
Inside the UpdatePanel there I dynamically add a Control (also containing a ScriptManagerProxy) and from that control I need to run some JavaScript code.
DynamicControl.ascx:
<script type="text/javascript">
function doSomething() {
alert(1);
}
</script>
DynamicControl.ascx.cs:
public void Page_Load(object sender, EventArgs e)
{
...
ScriptManager.RegisterStartupScript(
this.Page, this.GetType(), "scriptID",
"<script type='text/javascript'>doSomething();</script>", false);
My problem is that the function "doSomething()" is never called and i dont know why. :S
Edit: It is called but not directly when i add the control.
If I do code like this, there will be an alertwindow:
"<script type='text/javascript'>alert(1);</script>"
Ok I think i need to add some more information:
The control is dynamical added inside a jQuery Dialog. And I found out that the javacode is first executed after i close and then open the dialog. Some kind of event is triggered so that the code is executed there i think. Is it possible to force this event? so the scripts are executet directly when the control is added ?
placeHolder.Controls.Add(dynamicReportControl);
This c# code doesn't execute the javascript tag immediately ?
Please try something like this
ScriptManager.RegisterStartupScript(
this.UpdatePanel1, this.UpdatePanel1.GetType(), "scriptID",
"<script type='text/javascript'>doSomething();</script>", false);
Where UpdatePanel1 is your UpdatePanel
Try setting the addScriptTags argument to true, and remove the script declaration from your code.
Is that code only supposed to run on every request? If so, why not just add this code to the ASCX:
window.onload = doSomething();

use javascript value and doPostback?

i have a page where on click of a button, a javascript function runs. It then aggregates some data and places the data on a hidden field in this page. It then opens a new window. This new window picks up this aggregated data like so :-
$('#accepted').val(window.opener.$('#accepted').val());
where accepted is the hidden field in both parent and child window (no runat="server" was used). The issue now is that i require this data to databind two grids. Currently I've done a doPostback on both grids, but what i really want to do is doPostback for the form once and handle the databinding the PageLoad event. So two questions :-
1) How do i doPostback the form?
2) How do i do this while still being able to differentiate from the actual form submission?
To post the form you should just be able to add a call to __doPostback in your javascript, after the accepted field is set. You can use the EventTarget and EventArgument parameters of the __doPostback to control the binding in your grid.
So, you could put this in your js:
__doPostback('rebindGrid', '');
and then this in your page load event:
if (Request.Form["__EVENTTARGET"] == "rebindGrid")
{
//....Do so stuff
}
In order to tie it in more directly with the postback model I wrap mine with some C#
C# Extension Method
public static string GetPostBackLink (this Control c, string argument = "") {
return c.Page.ClientScript.GetPostBackEventReference(ctl, argument, true) + ";";
}
ASPX
<asp:LinkButton id="lnkDoThis" runat="server" onclick="lnkDoThis_Click"
style="display: none;"></asp:LinkButton>
<asp:HiddenField id="hdnParamHolder" runat="server" />
JS
function DoSomething(param) {
$("[id$='hdnDealTemp']").val(param);
<%= lnkDoThis.GetPostBackLink() %>
}
CodeBehind
protected void lnkDoThis_Click (object sender, EventArgs e) {
var myParam = hdnParamHolder.Value;
// Do server actions here
}
As for the opening in a second window ... I am not sure I follow when you want this to happen? If it is after the postback you will need to read from the hdnParamHolder control when the page reloads.

insert javascript only on page postback

I'm sure this is fairly straightforward but i'm having trouble getting it to work. I want to add a javascript function to my page, but only when the page postsback.
So I have a button that calls some server-side code, and when it is finished and the page is re-loading I want the javascript function to be called.
Thinking about this i guess I could just add a hidden variable and set it when the button is clicked, but i think i'd rather just insert the javascript onto the page when it is loading back.
Is this possible, or even a good way to do it?
Thanks,
Neil
Edit: Okay this is my OnClick method in the C# code.
protected void Save(object sender, EventArgs e)
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "<script type=\"text/javascript\">alert('hello world');</script>");
EnforcementMatch(false);
EnforcementMatch(true);
ApplicationNotMatch();
ApplicationMatch();
Response.Redirect(Request.Url.ToString());
}
Another Edit: Just realised that the response.redirect at the bottom reloads my page cancelling out the code I put in, duh!
You can use ClientScriptManager.RegisterClientScriptBlock
http://msdn.microsoft.com/en-us/library/btf44dc9.aspx
If you place it on the button click event, you don't have to worry if it's a postback or not.
You know about the IsPostBack function, right?
IsPostBack (MSDN)
if (IsPostBack)
{
ClientScript.RegisterClientScriptBlock()
}
This script will be fired with every single postback from updatepanel
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
alert('hello world');
});
</script>
Place it in a separate script block, only to be rendered on postback.
<script type="text/javascript" runat="server" visible="<%#this.IsPostBack %>">
TheCode();
</script>

Display a "Yes / No" alert box in C# code behind

I am trying to display a "Yes / No" messagebox from codebehind in C#. I want to call an "AddRecord" procedure if the user clicks "Yes", and do nothing if the user clicks "No".
Ideally, I want to use the code below, but from codebehind:
OnClientClick = "return confirm('Are you sure you want to delete?');"
I search on SO and google, but was not able to find anything helpful.
on your Add Record button, just do the following:
<asp:button ID="AddRecordbutton" runat="server" Text="Add Record"
onclick="AddRecordButton_Click" onclientclick="return confirm('add record?');" />
In your code behind, just put the add record code in your AddRecordButton_Click event handler. It will only be called if they click Yes on the popup.
Alternatively, you could have your codebehind assign the onclientclick code when the button is initially rendered.
For example:
protected void Page_Load(object sender, EventArgs e) {
AddRecordButton.OnClientClick = #"return confirm('Add Record?');";
}
No, you don't.
You seem to be misunderstanding that basic concept of webpage.
An ASPX page is a short program, which starts-up, generates seem HTML, and then terminates. The HTML is then sent across the Internet to the users browser. EVERYTHING you do in a codebehind must be complete before the user ever sees any of it.
You really want a javascript dialog box. (Actually, from what you describe, you could just create a messagebox-looking div in HTML with a standard HTML form on it.)
To display an actual messagebox you will need javascript as it is done on the client-side. For whatever reason, if you cannot use javascript, you could do what AEMLoviji has suggested and "fake" it with some cleverness.
Note that you do not need jQuery to display a messagebox, simple javascript will suffice.
If you use the Ajax Control Toolkit Modal Popup Extender on a Panel with your two buttons this will fire an event on the server which can be handled and execute whichever method/functions you wish
See here for an example
Use RegisterStartupScript
ScriptManager.RegisterStartupScript(this, GetType(), "unique_key",
"element.onclick = function(){ return confirm('Are you sure you want to delete?'); };",
true);
To show yes/no
<script>
function AlertFunction() {
if (confirm('Are you sure you want to save this thing into the database?')) {
$('#ConfirmMessageResponse').val('Yes');
} else {
$('#ConfirmMessageResponse').val('No');
}
}
</script>
to handle it from .net side:
string confirmValue = ConfirmMessageResponse.Value;
if (confirmValue == "Yes")
{...}

Categories