How to perform postbacks with Fluent Ribbon |
By default, ButtonDefinition and other Fluent Ribbon button definitions, provide ability to set up javascript actions for buttons, using CommandJavaScript field. But, sometimes, server side processing is needed.
This article describes, how developer can perform postbacks with Fluent Ribbon API.
First of all, you will need to define constant with postback identifier.
const string RibbonPostbackId = "MyPostbackEvent";
Next, pass this identifier into __doPostBack javascript subroutine in your ribbon button definition.
new ButtonDefinition() { Id = "PostbackButton", Title = "My postback button", CommandJavaScript = String.Format("__doPostBack('{0}','');"), RibbonPostbackId) }
In your ContextualWebPart descendent, add this code to CreateChildControls method:
if (this.Page.Request["__EVENTTARGET"] == RibbonPostbackId) { // do whatever you need }
Let's look at a little more complex example.
Consider, you have textbox at your ribbon, and you want to get user input from this textbox from your codebehind, when your ribbon button is pressed.
Full-qualified Id for this textbox is "Ribbon.MyContext.Tab.PostbackGroup.TextBox".
Here is the solution:
public class VisualWebPart1 : ContextualWebPart { private const string textBoxPostbackId = "MyTextBoxPostbackId"; private const string textBoxId = "Ribbon.MyContext.Tab.PostbackGroup.TextBox"; public override ContextualGroupDefinition GetContextualGroupDefinition() { return new ContextualGroupDefinition() { Id = "MyContext", Title = "VisualWebPart1 Tools", Tabs = new TabDefinition[] { new TabDefinition() { Id = "Tab", Title = "My tab", Groups = new GroupDefinition[] { new GroupDefinition() { Id = "PostbackGroup", Title = "Postback group", Template = GroupTemplateLibrary.ThreeRowTemplate, Controls = new ControlDefinition[] { new LabelDefinition() { Id = "Label", Title = "Enter your data:", Image = new ImageDefinition() { Url16 = "/_layouts/images/wpedit.gif" }, ForId = "TextBox" }, new TextBoxDefinition() { Id = "TextBox", InitialValueJavaScript = "return '';" }, new ButtonDefinition() { Id = "Button", Title = "Save!", Image = new ImageDefinition() { Url16 = "/_layouts/images/saveitem.gif" }, CommandJavaScript = String.Format("__doPostBack('{0}',{1});"), textBoxPostbackId, "document.getElementById('" + textBoxId + "').value") } } } } } } }; } public override CreateChildControls() { // ... if (this.Page.Request["__EVENTTARGET"] == textBoxPostbackId) { string textBoxValue = this.Page.Request["__EVENTARGUMENT"]; // do whatever you need with textBoxValue } // ... } }