Setting web part properties dynamically in your code

  Previous topic Next topic JavaScript is required for the print function Mail us feedback on this topic! Mail us feedback on this topic!  

In some cases, you may need to set the value of the web part in your code, depending on some particular business rules. In such case, you need to create a new ASCX user control and place the original web part to this user control. In the user control code, you can implement your custom logic and set the properties appropriately.

 

The following example shows how you can dynamically set the WHERE condition (WhereCondition) property of the Repeater web part based on the fact that the current user is or is not authenticated. It uses the standard News document type with custom boolean field Show to public users (ShowToPublicUsers).

 

1.Open the web project in Visual Studio.
 
2.Create a new folder under the project root called by the code name of your website, in our case CorporateSite. It will ensure that your user controls will be exported with the site when deploying the site to the live server.
 
3.Create a new user control under the folder CorporateSite and call it NewsRepeater.ascx.
 
4.Drag and drop the CMSWebParts/Viewers/cmsrepeater.ascx on your user control. You could alternatively use the CMSRepeater server control as well, but this is not the purpose of this example. Set its properties like this:
- ID: RepeaterWebPart1
- ClassNames: cms.news (document types)
- Path: /news/%
- TransformationName: cms.news.preview
- SelectedItemTransformationName: cms.news.default
 
5.Add the following code to the code-behind of your user control:

 

[C#]

 

protected void Page_Init(object sender, EventArgs e)

{

  if (CMS.CMSHelper.CMSContext.CurrentUser.IsPublic())

   {

      // public user - show only public news

      this.RepeaterWebPart1.WhereCondition = "ShowToPublicUsers = 1";

      this.RepeaterWebPart1.ReloadData();

   }

}

 
This will set the WhereCondition property value dynamically depending on whether the user is signed in. Save all changes.
 

6.Go to Site Manager -> Development -> Document types -> News and add a new field called ShowToPublicUsers of type boolean.
 
7.Go to CMS Desk -> Content, choose Home, switch to the Design tab and a new web part General/User control to the zoneBottom zone. Set the User control virtual path property value to ~/CorporateSite/NewsRepeater.ascx.
 
8.Edit some news in the /News section of the website and set the Show to public users value to Yes.
 
9.Sign out and see the home page. You should see only news items that you marked as Show to public users.

 

You have learned how to dynamically set the web part properties based on your custom logic.

 

Page url: http://devnet.kentico.com/docs/devguide/index.html?setting_web_part_properties_dynamically_in_code.htm