开发者

How do I cause a Postback?

开发者 https://www.devze.com 2023-03-18 09:49 出处:网络
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.

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
      开发者_JS百科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.

0

精彩评论

暂无评论...
验证码 换一张
取 消