When I load page I load this script:
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(),
"question",
"<script type = 'text/javascript'>if(confirm('Are you sure you want to do this?')) return true; else return false;</script>",
false);
I don't know how to handle when user click on yes to do something in code behind and when click on no to do some other thing?
How to handle this click in code behind?
if you are returning true/false, then in the code behind you will only get true.
To get values for false also you will have to create another function.
The best method that i like is setting the value of the return parameter in hiddenfield. And the getting this variable in codebehind and the working accordingly.
You have already have code for that.
You can only call javascript functions on Yes or NO. But Javascript function can call codebehind webmethods using Ajax.
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(),
"question",
"<script type = 'text/javascript'>if(confirm('Are you sure you want to do this?')){[Call Function for Yes]} else{ [Call Function for No or Cancel];}</script>",
false);
Other than the WebMethods technique, you also have an option of using the __doPostBack method to hit code-behind from your javascript code. More info on its usage at http://aspalliance.com/895_Understanding_the_JavaScript___doPostBack_Function.all, http://dopostback.net/.
A limitation of using WebMethods is, since they are always static, your non-static fields, methods, and controls won't be accessible inside them. http://forums.asp.net/t/1531113.aspx/1.
Related
I have an Update panel where a button and a grid are added as follows: this._UpdatePanel.ContentTemplateContainer.Controls.Add(this._BtnSave); this._UpdatePanel.ContentTemplateContainer.Controls.Add(this._AssignGrid);
On click of this button I am calling a function which resides in a different class AssignedGrid.cs.
this._AssignedGrid.getSelectedRows();
AssignedGrid.cs inturn calls a javascript function as follows:
public void getSelectedRows()
{
this.Page.ClientScript.RegisterStartupScript(Page.GetType(), "GetSelectedItems", "<script type='text/javascript' language='javascript'>GetSelectedItems();</script>");
}
But this javascript function is never called! Please let me know if I am calling the function the proper way.
This should work,
ScriptManager.RegisterStartupScrip(this.Page, this.Page.GetType(), "GetSelectedItems", "GetSelectedItems();", true);
The first parameter of the Script manager expects a page object (http://msdn.microsoft.com/en-us/library/bb310408(v=vs.110).aspx)
This is probably a user control, web control, etc and not an actual page object, as such it doesn't work. The only time this works is if you are in the context of a page, e.g. like a class that inherits from page.
So just send it the page object explicitly.
Once you have that, if it's not getting called, use a browser like Chrome, open the developer tools (f12) and go to the console window and look for javascript errors. If it was called but wasn't found you should see "GetSelectedItems does not exist" or a similar error. And that would mean your function is being declared and loaded after the code that calls it was inserted in the dom order by the ScriptManager.
The ScriptManager will insert the code call at the end of the page before the close tag, so define GetSelectedItems in the tag or somewhere above it.
You dont have to give script tags
ScriptManager.RegisterStartupScript(this, GetType(), "GetSelectedItems", "GetSelectedItems();", true);
Right now I have a radgrid that is filled with checkboxes. If I click on a check box it calls my code behind checkchanged. In check changed it checks and see if that item is active if its not it throws an alert. I want to change that alert to a confirm but the radajaxpanel doesn't appear to have a method for confirm so I figure I need to create one in javascript and call it in the code behind.
What I have now
else
{
RadAjaxPanel1.Alert("The event you selected is currently In-Active");
}
So I assume I would need to change that to a call of the javascript or something similar to call for a confirm and then return the response in the codebehind to either continue or stop.
EDIT: If this helps maybe what I am trying to explain is. On codebehind trigger a javascript method to run and return a value for my codebehind to evaluate and continue or stop running.
EDIT 2:Or what I want to change is on clientclick it calls the javascript and if the javascript return Yes then it calls the codebehind. Maybe that is more likely and possible.
I need to cause a postback in c#, how can i do this? (It can not be through a button or any other element) Just want to cause a postback if a condition is met.
something like
If(so and so)
Postback now!
else
Do not post back
From the comments it looks like you are using telerik's RadTabs. You could potentially set AutoPostBack to true on the tab control so that it would force a refresh whenever the user switches tabs.
http://www.telerik.com/help/aspnet/tabstrip/tab_server-side%20events.html
Your question does not make sense.
C# code runs on the server, in response to a postback.
Until a postback happens, no code can run.
You may want to trigger a postback in Javascript, which runs in the browser.
Some didactic contextualization: whatever piece of code you are trying to call in your "second postback", just call it in your "first postback" already!
Example:
You have a method you want to call, say, a Button_Click in your "second postback"? Just call it in you "first postback":
btnSaveClick(btnSave, null);
You can always do a Response.Redirect(Request.RawUrl);.
You'll want to be careful that you don't cause an endless redirect loop.
To force a postback in Server code, use ClientScript.GetPostBackEventReference() to generate the javascript code that does the postback. Then add a startup script in your event handler that calls the postback javascript.
aspx:
// Do an empty postback that doesn't do anything.
function doPostback() {
<%= ClientScript.GetPostBackEventReference(btnDoPostback, String.Empty) %>;
}
<asp:Button ID="btnDoPostback" runat="server" OnClick="btnDoPostback_Click" Style="display: none;" />
cs:
if (!IsPostBack) {
ScriptManager.RegisterStartupScript(this, this.GetType(), "dopostback", "doPostback();", true);
}
protected void btnDoPostback_Click(object sender, EventArgs e)
{
}
You can't do a postback in your code-behind. Your code-behind code IS your postback code. Why are you trying to do this? Maybe we can help you in your program logic
Did you want to call the page again? You can do this with a Response.Redirect
Do you mean on your .aspx/cshtml pages? If so use jquery's $.post
If you really are in a controller (and you are already running in response to a postback) then you should probably refactor your code so that whatever logic you want to call (via your 'second post' back) can be called from your existing location as well as your other Post action.
How can I write JavaScript code in asp.net in code behind using C#?
For example:
I have click button event when I click the button I want to invoke this java script code:
alert("You pressed Me!");
I want to know how to use java script from code behind.
Actually, this is what you need:
string myScriptValue = "function callMe() {alert('You pressed Me!'); }";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "myScriptName", myScriptValue, true);
Copy all of javascript into string and then register it into your aspx page in code-behind. Then in aspx page, you can call the javascript function whenever you want. You should write this code in Page_Load method in C# page.
Have a look at the ScriptManager class' RegisterClientScriptBlock and RegisterStartupScript methods.
One way to put some javascript onto the page into a specific location do this:
ASP.Net
<script type="text/javascript">
<asp:Literal id="litScript" runat="server" />
</script>
C#
litScript.Text = "alert("Hello!");"
Of course, you can put anything in there, and I'd recommend a javascript library.
Using the Scriptmanager is also an option.
Not an answer, but a suggestion.
Mixing your js within your code-behind can come back to haunt you, I agree with Adrian Magdas.
Anytime you need to make a simple change/update to your javascript you'll have to re-build your project, which means re-deploying instead of simply pushing out a single .js file.
Something like:
btnSomething.ClientClick = "alert('You pressed me!');";
You might also want to read up on the ScriptManager control and outputting blocks of script.
The right answers usually is "You don't". It's better to define your code in a .js file and use jQuery to hook-up the desired events.
$(document).ready(function() {
$('#myBtn').click(function() {
alert('Handler for .click() called.');
});};
If you want to register a script that will be used in connection with an UpdatePanel (AJAX) use ScriptManager class as Sani Huttunen pointed.
Otherwise you should use the class ClientScriptManager (methods Page.ClientScript.RegisterClientScriptBlock or Page.ClientScript.RegisterStartupScript)
As other user pointed, normally registering a script on the code behind can and should be avoided. It's not a very nice practice and you should do it only in cases where you have no other option.
Response.Write("<script language='javascript'>alert('You pressed Me!');</script>");
I encouter some postback issue when using GetPostBackEventReference. Here is the Scenario:
I have a javascript modal popup dialog and got a button in this modal dialog which used to select things (this is NOT an asp:button control)
When this javascript dialog HTML button is clicked, it will call the MS AJAX web service call by the javascript: eval() method. And this MS AJAX web service call is dynamically generated. So the code is like this:
var serviceCall = svcCall + "(" + parameters + ")"; //dynamically generate the MS AJAX web service call here
eval(serviceCall);
//use eval to trigger the MS AJAX web service call
As you may all know, after complete the MS AJAX web service, you can define a callback function to handle the completion:
function OnComplete(result, userContext, methodName) {
//force to call postback manually
eval($(userContext[0]).val());
//close the javascript dialog here
}
As I have mentioned before, the MS AJAX web service call is built dynamically, and when the MS AJAX web service call is construct, it will be passing a userContext which contain the postback value (i.e. "__doPostBack('ctl00$ContentPlaceHolder1$btnSelectUser','')", so when the javascript eval() is called, it simulate a asp:button click postback.
The userContext[0] basically holding a asp:hidden field's ClientID, and the hidden field's value is set during the Page_Load event:
protected void Page_Load(object sender, EventArgs e)
{
btnSelectUser.ValidationGroup = "popupSelect";
btnSelectUser.CausesValidation = false;
this.hdnBtnPostback.Value = Page.ClientScript.GetPostBackEventReference(btnSelectUser, string.Empty, false);
}
As you can see, this is how I bound the asp:button (i.e. btnSelectUser) 's Click Event to the asp:hiddenfield using the GetPostBackEventReference, and set the registerForEventValidation argument to false. I have also tried to use different ValidationGroup and set the CausesValidation to false, but no hope. :(
In summarize, I bound the asp:button's Click PostBackEventReference(i.e. __doPostback(....)) to the asp:hidden field's Value attribute, and using javascript eval() to eval this hidden field's value in order to manually trigger postback.
p.s. the btnSelectUser is an asp:button control and used to call out the javascript modal dialog.
Ok, here is the Problem:
In the same page, there is some asp:validator, e.g. and , and of coz, when the page run into error, this validator and callout will display to the user. e.g. When the user didn't fill in anything and submit the form, the ValidatorCalloutExtender will display a ballon and tell the user. Imagine one of this ballon/validatorCalloutExtender come out and on top of your screen at the moment.
Then you click the btnSelectUser (asp:button) to show the javascript modal dialog, and in the dialog, you Add some users, and once you hit the SELECT button inside this modal dialog, a MS AJAX web service is trigger as mentioned above, and once this web service is complete, it eval() the asp:hidden field's value (i.e. __doPostback(...))......and do the postback manually.
However, because of the validatorCalloutExtender ballon has display, it somehow cannot trigger the postback in this way, but when I close the ballon/validatorCalloutExtender, the manual postback using eval() is just working fine. Even more strange is that, when the ballon is displayed, the first time I click the SELECT button inside this modal dialog it doesn't fire the postback, however, if I do the same thing again (i.e. open up the javascript dialog, and choose some users, then click the SELECT button again). It able to do the manual postback....and I don't understand why the first time doesn't work.
This has really drive me crazy, hope anyone here can help, would be really appreciate. Thank you so much folks. :)
Have a nice day. Looking to heard from you all shortly.
When you call __doPostBack(eventTarget, eventArgument) a form submission is triggered:
This from post will proceed if WebForm_OnSubmit(); return true.
WebForm_OnSubmit result depends on ValidatorOnSubmit result, which in turn depends on
ValidatorCommonOnSubmit result if Page_ValidationActive == true.
Now if you are still with me, as in the function below:
function ValidatorCommonOnSubmit() {
Page_InvalidControlToBeFocused = null;
var result = !Page_BlockSubmit;
if ((typeof(window.event) != "undefined") && (window.event != null)) {
window.event.returnValue = result;
}
Page_BlockSubmit = false;
return result;
}
The result of ValidatorCommonOnSubmit depends on Page_BlockSubmit, so the only thing to block your postback is Page_BlockSubmit == true, it has nothing to do with validation callouts.
I was unable to simulate your case, but if you could post a full code sample it will help me track down the issue.