Is there a way to define the file upload controls using a Razor helper in ASP.NET MVC3?
3 Answers
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' />
}
-
1
-
12
-
<input type='file' name='FilePath' id='FilePath' />
FilePath is given as the model property name,So you can use it like any other control.– PAVITRAAug 30, 2015 at 12:45
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/
-
3That 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/…– PaukMar 1, 2011 at 15:11
-
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/>
}
-
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. Jan 25, 2015 at 18:27