Telerik Extensions for ASP.NET MVC

This topic shows how to use the Upload UI component in an ASP.NET MVC application.

Important

All Telerik UI components need a ScriptRegistrar component in order to output their JavaScript objects and register their JavaScript files. The ScriptRegistrar component should be defined *after* all other UI components in the page. If you create the components on the client-side and do not use the MVC extensions, you need to manually register all requried JavaScript files. For further information check this help topic (Step 4 - Register Scripts)

Prerequisites

Before proceeding make sure that:
  • You have all the required components installed.
  • Make sure that your ASP.NET MVC project refers the Telerik.Web.Mvc.dll assembly and you have a ScriptRegistrar and a StyleSheetRegistrar defined in your application (either in the master page or in the view where you are going to use the Upload UI component).
  • All required JavaScript and CSS files are properly copied to your project. This is outlined in here - steps 4 and 5.

Introduction

The Upload component uses progressive enhancement to deliver better file uploading experience for both end-users and developers.

It supports both asynchronous and synchronous uploading in all current browsers. In addition to the baseline functionality, the Upload uses the latest standard developments to deliver advanced features such as drag & drop support and progress tracking in modern browsers.

Upload Declaration

The following example shows how to setup an asynchronous upload that saves the uploaded files in the App_Data folder. The default template for a new ASP.NET MVC application is used.

Asynchronous upload

  1. Declare the control in the Index view.

    CopyC#
    <%= Html.Telerik().Upload()
            .Name("attachments")
            .Async(async => async
                .Save("Save", "Home")
            )
    %>
    • The Name is used to specify the unique name of the Upload component. It is used to set the id and name HTML attributes. Setting the name is mandatory and exception would be thrown otherwise.
    • The Save action that will receive the uploaded files is configured in the Async section.
  2. Implement the Save controller action.

    CopyC#
    public ActionResult Save(IEnumerable<HttpPostedFileBase> attachments)
    {
        // The Name of the Upload component is "attachments" 
        foreach (var file in attachments)
        {
            // Some browsers send file names with full path. We only care about the file name.
            var fileName = Path.GetFileName(file.FileName);
            var destinationPath = Path.Combine(Server.MapPath("~/App_Data"), fileName);
    
            file.SaveAs(destinationPath);
        }
    
        // Return an empty string to signify success
        return Content("");
    }
  3. Build and run the application. The uploaded files will appear in the App_Data folder.

Next Steps

See Also