I'm writing an MVC 5 web application to update blog posts. I want to be able to have the user upload a video to the content folder and then store the filename as a string in the database. However, I seem to be missing one essential piece though.
I have a method to update the posts which is working except for the video part.
public ActionResult Update(int? id, string title, string body, DateTime dateTime, string tags, Video video)
{
if (!IsAdmin)
{
return RedirectToAction("Index");
}
var post = GetPost(id); // get the post object
post.Title = title;
post.Body = body;
post.DateTime = dateTime;
post.Tags.Clear();
post.VideoFileName = UploadVideo(video);
I have created a class for the Video with one property.
public class Video
{
public HttpPostedFileBase File { get; set; }
}
Then a method in the same class as the Update
method to upload the video and return the filename.
[HttpPost]
public string UploadVideo(Video video)
{
if (video.File.ContentLength <= 0) return null;
var fileName = Path.GetFileName(video.File.FileName);
if (fileName == null) return null;
var path = Path.Combine(Server.MapPath("~/Content/Videos"), fileName);
video.File.SaveAs(path);
return fileName;
}
Then I have a View for the Update method but I don't know how to get the video object from this View into the Update method so that I can pass it to the UploadVideo
method.
<form action="@Href("~/Posts/Update")" method="post" id="postForm">
@if(Model.Id != -1)
{
<input type="hidden" name="id" value="@Model.Id"/>
}
@{ var dateTime = Model.DateTime.Year > 2000 ? Model.DateTime : DateTime.Now; }
<input type="text" name="dateTime" value="@dateTime "/> Date<br />
<input type="text" name="title" value="@Model.Title " /> Title<br />
<input type="text" name="tags" value="@ViewBag.Tags " /> Tags<br />
<textarea name="body" rows="10" cols="80">@Model.Body</textarea><br />
<br/>
<br/>
<input type="file" name="video" />
<br/>
<br/>
<input type="submit" name="submit" value="Submit" />
</form>
Using <input type="file" name="video" />
results in the video object being null when passed into the Update method.
How would you pass in the video file to the Update method with all the other text data set in the View such as dateTime
,title
,tags
and body
?