Model
public partial class Assignment
{
public Assignment()
{
this.CourseAvailables = new HashSet<CourseAvailable>();
}
public string AssignmentID { get; set; }
public Nullable<System.DateTime> SubmissionDate { get; set; }
public string Status { get; set; }
public Nullable<decimal> Mark { get; set; }
public string Comments { get; set; }
public string FileLocation { get; set; }
public virtual ICollection<CourseAvailable> CourseAvailables { get; set; }
}}
Controller
public ActionResult Create(Assignment assignment)
{
if (ModelState.IsValid)
{
db.Assignments.Add(assignment);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(assignment);
}
View
<div class="editor-field">
<%: Html.TextBoxFor(model => model.FileLocation, new { type="file"})%>
<%: Html.ValidationMessageFor(model => model.FileLocation) %>
</div>
How do I store a file if I wanted to store the file into the server/path folder and in the database I only want to store the Path name/string.
Here's how I did it:
View.cs
I was using
HomeController
, so you create theUpload
function there. I'm also including how you might store the file contents in the database, not just the location, and the code below makes use of theAssignment
model that was provided, but I'll also show how I saved it to the database in my case with a model I created for my table,ITEM_ATCHMT
.You shouldn't have to pass in a model & pass it back if all you have is a FileUpload control on the page and aren't populating data on the view with it, so this function doesn't do that, and my View doesn't use a model - yours may be different and you may want to keep your model being passed in, returned, if used on your view.
I set mine up for multiple objects to be posted at one time, so I had a
List<ViewDataUploadFilesResult>
that received their data and would get iterated through in the process of saving each of the files and their metadata to the database. You could use it to simply save one file at a time, though, so I've added the code for that and commented out the parts for the multiple files. Hopefully it doesn't confuse anyone - just 2 different ways of doing the same thing, in the end.HomeController.cs
Additional Model
ViewDataUploadFilesResult.cs
For me, instead of using this whole ViewModel, this is an actual model for my Attachments table:
And say I wanted to associate it with this item:
To save any data using Entity Framework, you just need to fill that model, then do a
.SaveChanges()
on your context:And if
ITEM_ID
is set up with auto-incrementing:you can upload file and save its url in the database table like this:
View:
Action:
Details:
For better understanding refer this good article Uploading a File (Or Files) With ASP.NET MVC