Reputation: 75083
As there is no helper for File Input, how can we safely handle a file input?
If it better just to have a button
<input type="button" value="Upload File" />
and handle this in a new pop-up page/window?
shall I have the
<input type="file" value="Upload File" />
but how would I handle this in the code?
#region General
//
// GET: /Content/General
public ActionResult General()
{
GeneralModel model = new GeneralModel();
return View(model);
}
[HttpPost]
public void General(GeneralModel model)
{
}
#endregion
The model will not be populated with the file so I need to do something else ... just don't know what :(
Any help is greatly appreciated.
Thank you.
Upvotes: 0
Views: 910
Reputation: 1038830
The input should have a name:
<input type="file" name="File" />
Then to handle the uploaded file you could add a property to your view model:
public class GeneralModel
{
// The name of the property corresponds to the name of the input
public HttpPostedFileBase File { get; set; }
...
}
and finally in your controller action handle the file upload:
[HttpPost]
public void General(GeneralModel model)
{
var file = model.File;
if (file != null && file.ContentLength > 0)
{
// The user selected a file to upload => handle it
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/Uploads"), fileName);
file.SaveAs(path);
}
return View(model);
}
Phil Haack blogged about file uploads in ASP.NET MVC.
Upvotes: 1