尝试上传多个视频时查看模型不工作

View Model Not Working While Trying to Upload the Multiple Videos

我正在使用视图模型上传多个视频,但视频没有上传。在使用视图模型代码工作罚款之前,但现在当我点击上传按钮并调试时,HTTP post 上传操作中的视频对象为空,这是我的控制器代码

public ActionResult UploadedVideos()
{
    ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
    var q = db.Videos.Where(v => v.UserId == user.Id).ToList();
    return View(q);
}

[HttpPost]
public ActionResult Upload(List<Models.ViewModels.VideoView> videos)
{
    try
    {
        ApplicationUser user =    System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
        HttpFileCollectionBase files = Request.Files;
        //  Video video = new Video();
        foreach (var video in videos)
        {
            long time = DateTime.Now.Ticks;
            string path = Server.MapPath("~/Images/" + time + "_" + video.file.FileName);
            video.file.SaveAs(path);
            video.Path = path;
            video.DateTimeStamp = DateTime.Now;
            video.UserId = user.Id;
            db.Videos.Add(video);
        }
        db.SaveChanges();
        return RedirectToAction("UploadedVideos");
    }
    catch(Exception e)
    {
        return Json("Failed Error : "+e.Message,       JsonRequestBehavior.AllowGet);

     }
 }

查看代码为

@model Final.Models.ViewModels.VideoView
@{
    ViewBag.Title = "upload";
}
<h2>Index</h2>
@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{

    @Html.AntiForgeryToken()

    <div class="form-horizontal">

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control inputField" } })
                @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Category, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Category, new { htmlAttributes = new { @class = "form-control inputField" } })
                @Html.ValidationMessageFor(model => model.Category, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Tags, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Tags, new { htmlAttributes = new { @class = "form-control inputField" } })
                @Html.ValidationMessageFor(model => model.Tags, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.PrivacyStatus, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.PrivacyStatus, new { htmlAttributes = new { @class = "form-control inputField" } })
                @Html.ValidationMessageFor(model => model.PrivacyStatus, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextAreaFor(model => model.Description, new { @cols = "50", @rows = "5" })
                @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-horizontal">

            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control inputField" } })
                    @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(model => model.Category, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Category, new { htmlAttributes = new { @class = "form-control inputField" } })
                    @Html.ValidationMessageFor(model => model.Category, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(model => model.Tags, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Tags, new { htmlAttributes = new { @class = "form-control inputField" } })
                    @Html.ValidationMessageFor(model => model.Tags, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(model => model.PrivacyStatus, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.PrivacyStatus, new { htmlAttributes = new { @class = "form-control inputField" } })
                    @Html.ValidationMessageFor(model => model.PrivacyStatus, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.TextAreaFor(model => model.Description, new { @cols = "50", @rows = "5" })
                    @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
                </div>
            </div>
            </div>

            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                </div>
                <div class="form-group">
                    <input type="file" name="file" multiple id="file" /><br />

                    <div id="all-progress-bars"></div>
                    <input type="submit" value="Save and Upload" href="javascript:void(0)" id="bb" class="btn btn-default" />


                    <span id="display"></span>
                </div>
            </div>
        </div>
}

这是我的视图模型

public class VideoView:Video 
{
    public HttpPostedFileBase file { get; set; }
}

如果您希望用户上传多个视频,包括为每个视频添加属性,您需要从表示您想要编辑的视图模型开始

public class VideoVM
{
    public string Title { get; set; }
    public string Description { get; set; }
    .... // other properties as required
    public HttpPostedFileBase File { get; set; }
}

并在 GET 方法中,创建一个集合以传递给视图

public ActionResult Upload()
{
    List<VideoVM> model = new List<VideoVM>();
    for (int i = 0; i < 5; i++)
    {
        model.Add(new VideoVM());
    }
    return View(model);
}

视图将是

@model List<VideoVM>
....
@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    for(int i = 0; i < Model.Count; i++)
    {
        @Html.TextBoxFor(m => m[i].Title)
        @Html.TextBoxFor(m => m[i].Description)
        ....
        @Html.TextBoxFor(m => m[i].File, new { @type = "file" })
    }
    <input type="submit" value="Upload" />
}

这将 post 回到

[HttpPost]
public ActionResult Upload(List<VideoVM> model)
{
    foreach(VideoVM video in model)
    {
        if (video.File.ContentLength > 0)
        {
            continue;
        }
        string fileName = Path.GetFileName(video.File.FileName);
        string path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
        video.File.SaveAs(path);
        Video dataModel = new Video()
        {
            Title = video.Title,
            Description = video.Description,
            ....
            Path = path
        };
        db.Videos.Add(dataModel);
    }
    db.SaveChanges();
    return RedirectToAction("UploadedVideos");
}

旁注:您在评论中指出您希望用户上传最多 5 个视频。上面的代码创建了所有 5 个。如果你想允许添加少于 5 个(并假设你的属性上有验证属性),那么你需要 javascript 为每个项目动态添加 html并更新集合索引器。如何实现这个例子,参考下面questions/answers