【问题标题】:ASP.NET MVC: view does not function well for file uploadASP.NET MVC:视图不能很好地用于文件上传
【发布时间】:2016-05-08 16:24:22
【问题描述】:

我正在尝试在我的视图中添加 上传文件 字段。 我编辑了我的 ViewModel 并在其中添加了以下行: 公共 HttpPostedFileBase ImageUrl { 获取;放; } 然后我添加了以下帮助文件上传:

        @Html.EditorFor(model => model.ImageUrl)

我也像这样更改了表单助手:

@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) 

但是,当我运行视图时,它会显示文件的内部字段:

我错过了什么导致这种情况?

【问题讨论】:

    标签: asp.net asp.net-mvc


    【解决方案1】:

    使用TextBoxFor 辅助方法。

    @using (Html.BeginForm("Create", "Home", FormMethod.Post,
                                              new { enctype = "multipart/form-data" })) 
    {
       @Html.TextBoxFor(s=>s.ImageUrl,new { type="file"})
       <input type="submit" />
    }
    

    甚至是纯 HTML

    @using (Html.BeginForm("Create", "Home", FormMethod.Post,
                                                     new { enctype = "multipart/form-data" })) 
    {
       <input type="file" name="ImageUrl" />
       <input type="submit" />
    }
    

    【讨论】:

    • 我不知道为什么这会在我的 ViewModel 中返​​回 null?我的 httppost 控制器看起来像这样 public ActionResult Create(ViewModelCreate viewModel) 并且 viewModel.ImageUrl 为空。
    【解决方案2】:

    确保模型对象上的 ImageUrl 属性如下所示:

    [DataType(DataType.Upload)]
    public HttpPostedFileBase ImageUrl { get; set; }
    

    然后,在您看来,只需像往常一样使用 HTML 帮助器的编辑器

    @Html.EditorFor(m => m.ImageUrl)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      • 2018-01-23
      • 2013-08-12
      • 2016-12-08
      • 2014-08-31
      • 1970-01-01
      相关资源
      最近更新 更多