Using AjaxUploader with MVC 3 Razor

  •  12-27-2010, 2:38 PM

    Using AjaxUploader with MVC 3 Razor

    Just thought I would post this for others that might be struggling with using AjaxUploader with MVC3 Razor syntax.  The problem I have been struggling with is that Razor automatically escapes Html code which is a good security practice.  The problem with AjaxUploader is the Uploader's Render() method which renders the html for injection into the view.  Since it renders Html, Razor's automatic scripting causes problems with inserting the html into your view. 
     
    Fixing this is a simple thing:  In your controller simply wrap the rendering call in a new HtmlString ie:
     
       [ChildActionOnly]
       [Authorize]
       public PartialViewResult UploadFiles()
       {
          using (CuteWebUI.MvcUploader uploader = new CuteWebUI.MvcUploader(System.Web.HttpContext.Current))
          {
    uploader.UploadUrl = Response.ApplyAppPathModifier("~/UploadHandler.ashx");
    //the data of the uploader will render as <input type='hidden' name='myuploader'> 
    uploader.Name = "myuploader";
    uploader.AllowedFileExtensions = "*.jpg,*.gif,*.png,*.bmp,*.zip,*.rar";
    //allow select multiple files
    uploader.MultipleFilesUpload = true;
    //tell uploader attach a button
    uploader.InsertButtonID = "uploadbutton";
    //prepair html code for the view
    ViewData["uploaderhtml"] = new HtmlString( uploader.Render());
          }
          return PartialView();
       }
    then in your view
    @using (Html.BeginForm())
    {
        <button id="uploadbutton" onclick="return false;">Select multiple files to upload</button>
        <!-- input type='hidden' id='myuploader' name='myuploader' -->
    <script type="text/javascript">
        function CuteWebUI_AjaxUploader_OnPostback() {
            //submit the form after the file have been uploaded:
            document.forms[0].submit();
        }
    </script>
        @ViewData["uploaderhtml"]
        
        }
           
      
        <!-- After posting the myuploader to server -->
        @if (@ViewData["UploadedMessage"] != null)
        { 

      @ViewData["UploadedMessage"]
            }
        


        

     
     
View Complete Thread