15

Is there a way to define the file upload controls using a Razor helper in ASP.NET MVC3?

3 Answers 3

27

There isn't an html helper for file inputs, but what is wrong with just doing

@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new {enctype = "multipart/form-data"})) {
    <input type='file' name='blah' id='blah' />
}
Sign up to request clarification or add additional context in comments.

3 Comments

No client side validation out of the box.
Beats nothing out of the box
<input type='file' name='FilePath' id='FilePath' /> FilePath is given as the model property name,So you can use it like any other control.
4

There is a FileUpload class in Microsoft.Web.Helpers... http://msdn.microsoft.com/en-us/library/microsoft.web.helpers.fileupload(v=vs.99).aspx

The best/only way I've found to get it is by using NuGet in VisualStudio. Search for package "microsoft-web-helpers" in the online repository. There is one problem I encountered, however. One of the package's dependencies is Facebook.Helper, which it will install at the same time. It will place a file called "Facebook???.cshtml" (forgot the exact name) in your project's AppCode directory. The problem is that the Facebook???.cshtml had some WebMatrix dependencies that I didn't have and didn't want to install. Simply deleting the Facebook.cshtml file (which I wasn't going to use, anyway) seemed to resolve the issue. After that, I was able to compile and debug as usual and use the FileUpload class.

Here's a tutorial I found that utilizes it:

http://blog.tallan.com/2011/02/04/using-mvc3-razor-helpers-and-jcrop-to-upload-and-crop-images/

2 Comments

That tutorial is OK, but it doesn't explain clearly what code goes where. I'd suggest this one instead since it's just about file uploading (not resizing images as well): blogs.planetcloud.co.uk/mygreatdiscovery/post/…
Pauk's link gave way to bitrot. Here's a Wayback link
0

USING RAZOR

@*requieres installing Asp helpers / you can do it her from NuGet or logging som admin in packages*@
@using Microsoft.Web.Helpers;
@{
    var fileName = "";
    if (IsPost) {
        var fileSavePath = "";
        var uploadedFile = Request.Files[0];
        fileName = Path.GetFileName(uploadedFile.FileName);
        fileSavePath = Server.MapPath("~/UploadedFiles/" +
          fileName);
        uploadedFile.SaveAs(fileSavePath);
    }
}

      @FileUpload.GetHtml(
        initialNumberOfFiles:1,
        allowMoreFilesToBeAdded:false, 
        includeFormTag:false,
        name: "Upload1",
        uploadText:"Upload")

    @if (IsPost) {
        <span>File uploaded!</span><br/>
    }

1 Comment

None of this IsPost login should be in the view, it all belongs in the controller, ideally split between two methods, one of which having the [HttpPost] decorator.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.