Avatars are images associated with user accounts. They can be displayed, for example, on a user's public profile. Avatars serves as graphical representations of users and are often used to personalize user contributions on websites.
Site users can manage avatars either in the administration interface or on the live site, depending on their privilege level:
By default, newly created or registered users do not have an avatar associated with them in the system.
Site administrators can configure the maximum size for user-uploaded avatar images in the Settings application under Security & Membership -> Avatars. The system resizes all uploaded avatar images to fit these constraints.
Before regular site users can use the avatar functionality, site developers need to implement support for displaying and manipulating user avatars.
The system provides the following API developers can leverage when implementing user avatar support on the live site (as part of the Kentico.Content.Web.Mvc namespace):
bool UpdateAvatar – sets or updates an existing avatar for the specified user. The avatar is bound to the user and cannot be selected by other users. When the users changes their avatar, their previous avatar is deleted from the system.
When processing uploaded files, the UpdateAvatar method checks whether the extension of the uploaded file is included in the list of allowed extensions in Settings -> System -> Files -> Upload extensions and resizes the image to fit the dimensions configured in the avatar settings.
string GetAvatarUrl – returns an application relative virtual URL (starting with ~/) for the avatar of the specified user.
void DeleteAvatar – deletes the avatar image associated with the specified user.
The following set of examples demonstrates the usage of the avatar API on the live site.
To display user avatars, call the Url.Kentico().AvatarUrl extension method in the code of your views. For example:
@using Kentico.Membership.Web.Mvc
@model Kentico.Membership.User
...
<img src="@Url.Kentico().AvatarUrl(Model.UserName, pathToDefaultAvatar: "~/Content/Images/default-avatar.png")" />
...This snippet renders an img tag with the given user's avatar. If the user has no avatar image assigned, it displays the image specified in the pathToDefaultAvatar parameter.
This section demonstrates the implementation of a simple avatar uploader. The uploader allows site users to change the avatar image associated with their account:
Tip: To view the full code of a functional example, you can inspect and download the LearningKit project (opens in a new tab) on GitHub. You can also run the LearningKit website by connecting the project to a Xperience database. Follow the instructions in the repository's README file.
Initialize an instance of IAvatarService in the controller class used to manage user account activities on your website.
private readonly IAvatarService avatarService;
private readonly IEventLogService eventLogService;
public AccountController(IAvatarService avatarService,
IEventLogService eventLogService)
{
// Initializes an instance of a service used to manage user avatars
this.avatarService = avatarService;
this.eventLogService = eventLogService;
}Add a new action that handles uploaded avatars and assigns them to users.
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize]
public ActionResult ChangeAvatar(HttpPostedFileBase avatarUpload)
{
object routevalues = null;
// Checks that the avatar file was uploaded
if (avatarUpload != null && avatarUpload.ContentLength > 0)
{
// Gets the representation of the user requesting avatar change from Xperience
var user = KenticoUserManager.FindByName(User.Identity.Name);
// Attempts to update the user's avatar
if (!avatarService.UpdateAvatar(avatarUpload.ToUploadedFile(), user.Id, SiteContext.CurrentSiteName))
{
// If the avatar update failed (e.g., the user uploaded an image with an usupported file extension)
// sets a flag for an error message in the corresponding view
routevalues = new { avatarUpdateFailed = true };
}
}
return RedirectToAction("EditUser", "Account", routevalues);
}The avatarUpdateFailed flag controls the display of an error message to the user in the corresponding view. It should be set to false by default in the controller action handling the uploader display (e.g., on the user account overview page):
public ActionResult EditUser(bool avatarUpdateFailed = false)
{
// Finds the user based on their current user name
User user = KenticoUserManager.FindByName(User.Identity.Name);
EditUserAccountViewModel model = new EditUserAccountViewModel()
{
User = user,
AvatarUpdateFailed = avatarUpdateFailed
};
return View(model);
}Update the corresponding view to render user avatars and add avatar update functionality. In this example, the form handling the avatar image submit is hidden and invoked when the user clicks on the Change avatar button. The submit() (opens in a new tab) method call bound to the onchange event of the text box form input ensures the form is immediately submitted after a user selects an avatar using the browser's file explorer.
@using Kentico.Membership.Web.Mvc
<div>
<h2>User Avatar</h2>
<div>
@* Generates a link to a user's avatar (or a default one if specified and a user avatar is not found).
Note that the properties constraining avatar dimensions do not work for default avatars. *@
<img src="@Url.Kentico().AvatarUrl(Model.User.UserName, maxSideSize: 500, width: 500, height: 500, pathToDefaultAvatar: " ~/Content/Images/default-avatar.png")" />
<br />
<button>
<div onclick="document.getElementById('avatarUpload').click()">Change avatar</div>
</button>
</div>
@* Displays an error message in case the user uploaded a file with an unsupported file extension.
Supported file extensions can be configured in Settings -> System -> Files -> Upload extensions in the Administration interface. *@
@if (Model.AvatarUpdateFailed)
{
<div>
<span>Please upload a valid image file.</span>
</div>
}
@using (@Html.BeginForm("ChangeAvatar", "Account", FormMethod.Post, new { enctype = "multipart/form-data", id = "avatarUploadForm", style = "display:none;" }))
{
// Generates a hidden field holding an anti-forgery token
// The Xperience API version of this method ensures tokens are correctly generated for pages where output caching is enabled
@Html.Kentico().AntiForgeryToken()
@Html.TextBox("avatarUpload", "", new { type = "file", id = "avatarUpload", accept = "image/*", onchange = "document.getElementById('avatarUploadForm').submit()" })
}
</div>The site's users can now change their avatars at will using the avatar uploader.
To allow users to delete their avatars, create a controller action that calls the IAvatarService.DeleteAvatar method:
[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult DeleteAvatar(int userId)
{
// Deletes the avatar image associated with the user
avatarService.DeleteAvatar(userId);
return RedirectToAction("EditUser", "Account");
}The method removes the avatar image from the user and deletes the associated avatar object from the system. You can then extend the view of the page where users manage their account, and add a HTML form that posts the user ID of the current user to the given action.