Setting web part properties dynamically in your code |
|||||
Setting web part properties dynamically in your code |
|
||
In some cases, you may need to set the values of web part properties 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 onto 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 if the current user is or is not authenticated. It uses the standard News document type with a custom boolean type field: Show to public users (ShowToPublicUsers).
1. Open the web project in Visual Studio.
2. Create a New folder under the project root called CMSGlobalFiles (if it doesn't already exist). This location will ensure that your user controls can be exported along with the site when it is deployed to the live server.
3. Create a new Web User Control under the CMSGlobalFiles folder and name it NewsRepeater.ascx.
4. Switch to the Design tab and drag and drop CMSWebParts/Viewers/Documents/cmsrepeater.ascx from the Solution Explorer onto your user control. You could alternatively use the CMSRepeater server control, 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. Now add the following to the code behind of your user control inside the CMSGlobalFiles_NewsRepeater class:
[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 current user is signed in. Save all changes. If your Kentico CMS project was installed as a web application, you must Build the project.
6. Go to Site Manager -> Development -> Document types -> News, add a New attribute () on the Fields tab and set its properties as shown below:
•Attribute name: ShowToPublicUsers
•Attribute type: Boolean (Yes/No)
•Field caption: Show to public users
•Field type: Check box
7. Go to CMS Desk -> Content, choose Home, switch to the Design tab and add () a new General/User control web part to the zoneCenter zone. Set the User control virtual path property value to: ~/CMSGlobalFiles/NewsRepeater.ascx
8. Edit some news document in the /News section of the website on the Form tab and check the Show to public users checkbox.
9. Sign out and view the home page. You should see only news items that you marked as Show to public users.
You have learned how to dynamically set web part properties based on your custom logic.