【问题标题】:MVC File upload with Custom Validation is null带有自定义验证的 MVC 文件上传为空
【发布时间】:2013-05-29 14:58:21
【问题描述】:

我正在上传和图像并根据此帖子验证其有效性: How to validate uploaded file in ASP.NET MVC? 但是,我的示例略有不同,因为我不仅收到了文件,还收到了模型的一些属性。但是,我的验证器总是触发,我调试并发现我的文件总是为空,所以验证器总是触发'false'。我不明白为什么,我的观点似乎是正确的。有什么想法吗?

namespace PhotoManagement.Models
{
public class Photo
{
    public virtual int PhotoId { get; set; }
    public virtual int ClientId { get; set; }
    public virtual string PhotoDescription { get; set; }
    [ImageValidation(ErrorMessage="Please select a PNG/JPEG image smaller than 10 MB")]
    [NotMapped]
    public HttpPostedFileBase File { get; set; }
}
}

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Photo photo)
    {
        if (ModelState.IsValid)
        {
            db.Photos.Add(photo);
            db.SaveChanges();
            // File upload occurs now
            var FilePath = Path.Combine(Server.MapPath("~/App_Data/" + photo.ClientId), photo.PhotoId.ToString());
            photo.File.SaveAs(FilePath);
            return RedirectToAction("Create");
        }
        else return View();
    }

@using (Html.BeginForm(new { enctype = "multipart/form-data" })) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)

<fieldset>
    <legend>Photo for @Session["Name"]</legend>

    <div class="editor-field">
        @Html.Hidden("ClientId",(int)Session["UserId"])
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.PhotoDescription)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.PhotoDescription)
        @Html.ValidationMessageFor(model => model.PhotoDescription)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.File)
    </div>
    <div class="editor-field">
        <input type="file" name="File" id="File"/>
        @Html.ValidationMessageFor(model => model.File)
    </div>

【问题讨论】:

  • 看看能不能上传文件,至少看看模型绑定是否正确。然后应用服务器端验证。
  • 您要上传的文件有多大?看看这是否有帮助:stackoverflow.com/questions/10856240/…

标签: asp.net asp.net-mvc entity-framework


【解决方案1】:

您使用了 错误的重载 Html.BeginForm 帮助器。

正确的称呼是这样的:

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

}

你在打电话:

Html.BeginForm(object routeValues)

代替:

Html.BeginForm(
    string actionName, 
    string controllerName, 
    FormMethod method, 
    object htmlAttributes
)

查看浏览器中生成的标记,您会发现根本区别。

【讨论】:

  • 你是我的英雄,我搜索了几个小时来解决这个问题。非常感谢!
【解决方案2】:

代替

public ActionResult Create(Photo photo)

试试

public ActionResult Create(Photo photo, HttpPostedFileBase file)

编辑:不要忘记在视图中将 HTTP 方法设置为 POST:

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

【讨论】:

  • 这有什么帮助?他已经在他的Photo 模型上拥有一个名为File 类型为HttpPostedFileBase 的属性。
  • 我以前遇到过这个问题,我通过这样做解决了这个问题。不要问我为什么......
  • 不,这不可能解决问题:-)
【解决方案3】:

模型中的文件总是会给你空值。为了获取文件:

[HttpPost]
        public ActionResult Create(UserViewModel model, 
FormCollection formCollection, HttpPostedFileBase file){

     /* Your code here */
    if(file==null)
    {
        ModelState.AddModelError("NoFile", "Upload File");
    }
}

这里的HttpPostedFileBase 文件会给你上传文件的完整对象。您可以检查目标文件的条件。不要忘记在视图中添加下面提到的验证消息。

@Html.ValidationMessage("NoFile")

【讨论】:

  • 哦不,您将包含多少次 file 参数?他已经将它作为他的照片视图模型的一部分。有这个文件参数是完全多余的,有这个 FormCollection 参数更完全是多余的。
  • 我在网上看到了很多Shalin的方法,但在我的情况下它并不适用,因为我无法使用模型属性进行验证。
猜你喜欢
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-08
  • 1970-01-01
  • 2014-09-06
相关资源
最近更新 更多