简体   繁体   中英

How do I cause a Postback?

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

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM