How do I cause a Postback? - c#

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.

Related

ASP.NET WebForms Confirm

I'm new to web programming with .NET.
I am developing a web page with webforms, and I want at a certain moment to programmatically show a modal window, for the user to accept or cancel, according to a question. Exactly what does the "confirm" function of JavaScript.
I tried to get it calling a JavaScript function:
Page.ClientScript.RegisterStartupScript (this.GetType (), "CallMyFunction", "MyFunction()", true);
But I need to do it without reloading the page, and I also need to control if the user has accepted or canceled and I do not know how to do it.
I've also tried getting it using the ModExPopupExtender control from DevExpress.
Can someone tell me a simple way to get what I want?
I can not understand how something so usual in web programming, and that PHP + javascript would not pose any problem can be so complicated.
All start in a one-button event on the code behind:
protected void btn1_Click(object sender, EventArgs e)
{
//I make a series of checks
//If certain conditions I want to show the confirm
//According to the user has chosen ok or cancel will perform a certain action
}
Onclientclick does not help me because before launching the "confirm" I have to do some checks on the server side.
Thank you very much.
You can use OnClientClick which is a property on most web controls.
I like to just bring up a simple confirm() dialog which executes the server code if the user clicks OK and does nothing if the user cancels the action:
<asp:Button runat="server" ID="btnSave" Click="btnSave_Click" Text="Save"
OnClientClick="return confirm('Are you sure you want to do this thing?');" />
You can do other things with it as well, but the key thing to remember is that anything you do in OnClientClick will happen before the page gets posted back to the server.
This is also perfectly valid:
<asp:Button runat="server" ID="btnSave"
OnClientClick="showModalConfirm('some message goes here');" ... />
<script>
function showModalConfirm(msg)
{
$(".modal .message").innerHtml(msg);
$(".modal").Show();
}
</script>
You can set the action that OnClientClick should perform in your codebehind in exactly the same way:
protected void Page_Load(object sender, EventArgs e)
{
btnSave.OnClientClick = "return confirm('Are you sure you want to do this thing?');";
}
You can use below code in c# to call javascript function. Below code will execute afterpostback() javascript function:
ClientScript.RegisterStartupScript(GetType(), Javascript, "javascript:afterpostback();", true);
And you can write code in javascript function to display any div or popup:
<script language="javascript" type="text/javascript">
function afterpostback() {
//Here you can write javascript to display div/modal
}
</script>
One way I've handled this previously was to have 2 buttons on the page. The first would be initially visible and labeled "Submit". The second would be initially hidden and labeled "Confirm". The "Submit" button would postback upon click and perform your server side checks/validation. If those checks failed, an appropriate error message would be displayed. If those checks passed, an appropriate "Please confirm your submission"-type message would be displayed, the "Submit" button would become hidden, and the second "Confirm" button would become visible. When that Confirm button was clicked, it would postback again and fully submit.
EDIT: I forgot to mention, there's a bit more to this that occurred to me after I initially posted. You'll have to protect the fields from being edited in the event the server-side verification is successful as you obviously don't want the user changing values and then clicking the Confirm button. That means disabling all the input controls - which could be a pain if you have a lot. You also have to give them a way to (intentionally) Edit in case the server side verification passes, you display the Confirmation, and they change their minds - so basically you'd need a third "Cancel/Edit"-type button that would put the form back in edit mode and show your initial Submit button.

How can I avoid PostBack on a LinkButton?

This is my LinkButton:
<asp:LinkButton OnClientClick="Page_ClientValidate('validPanel1'); if(Page_IsValid==false) { console.log('error'); return false; }" ID="linkPanel1" ValidationGroup="validPanel1">Check</asp:LinkButton>
if the page is not valid, ok, I get the summary. If it's valid, it do a postback to the server (also if I have return false).
I don't want this. I want a sort of "void" function (later, I catch the event through a jquery handler).
How can I do it?
Link button is designed to postback every time, since it is server side control.
If you want to avoid its postback, you will have to handle all the code clientside, by writting javascript function.
Try Following:
LinkButton1.Attributes.Add("onclick", "JSFunction();return false;")
here JSFunction() is javascript function.
This will not postback.

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!

Autopostback a page in Page_Unload

I want to autopost a page in Page_Unload. When I write Response.Redirect, I got error.
Want to achieve show Data List. I'm databinding it, but it shows after refreshing the page.
Can somebody help me?
protected void Page_Unload(object sender, EventArgs e)
{
...
DataList1.DataBind();
//autopostback in this line
}
You can't do anything like that in the Unload event.
Whe the Unload event happens, the page has already been rendered and sent to the browser, so it's too late to do anything to change the response.
Besides, making a postback from server code doesn't make sense, as that would simply create an eternal loop without anything ever being sent back to the browser. If you want to make a postback when something happens in the browser, you would do that using Javascript, not in the server code.
use the PreRender event instead of UnLoad.
Note: I know its old question but I believe some one would get use of this answer.

ASP.NET 2.0 - Need to programmatically click a link

Is there a way to click a link programatically, so that it has the same effects as if the user clicked on it?
Example:
I have an ASP.NET LinkButton:
<asp:LinkButton id="lnkExport" runat="server" CssClass="navclass">Export</asp:LinkButton>
I have a link on a sidebar directing to the .aspx page that has this linkbutton on it. For various reasons I can't have the code for the LinkButton executed until the page has refreshed -- so I am looking for a way to force-click this LinkButton in my code once the page is completely loaded. Is there a simple/doable way to accomplish this? If it involves triggering an event, please provide a code sample if you can. Thanks.
Triggering a click event programatically on a link will trigger the “onclick” event, but not the default action(href).
And since linkbuttons come out as hrefs, so you could try doing this with Javascript.
var lnkExport = document.getElementById('<%= lnkExport.ClientID %>');
if(lnkExport){
window.location = lnkExport.href;
}
I certainly think that, there is a design and implementation flaw which forces you to conclude as you described.
Well, invoking the click event means nothing but executing the event registration method.
So, the worst suggestion I can think of is, just call the function at what point you want to happen the click event like,
lnkExport_Click(lnkExport, new EventArgs());
Rashack's post show's how to do it. You can just do it in javascript.
function ClickLink() {
document.getElementById('').click();
}
If you want this to fire after some other event, you can add code in c# to add a call to that function on the client side when the page loads.
Page.ClientScript.RegisterStartupScript(
this.getType(),
"clickLink",
"ClickLink();",
true);
I'm not sure why you'd need your page to load if you're just wanting to programmatically click that link. I'd recommend using Response.Redirect() on the server side to redirect them to that page. Not sure if there are other extenuating reasons this simple approach won't work...
--Matt
If i understand what you're saying:
<asp:LinkButton id="lnkExport" runat="server" CssClass="navclass" onclick="lnkExport_Click">Export</asp:LinkButton>
then in your codebehind or whenever call the following when you need to...
lnkExport_Click( null, null );
and make sure you've got lnkExport_Click wired up.
protected void lnkExport_Click( object sender, EventArgs e )
{
//DO Whatever here
}
<button onclick="document.getElementById('<%=this.lnkExport.ClienID%>').click()">
click me</button>

Categories