为什么验证消息不能与 asp.net mvc 中的上传控件一起正常工作?

Why Validation Message didn't work correctly with Upload control in asp.net mvc?

我在 asp.net mvc 5 中有一个用于上传图片的表单。

一切正常,但 Validation Error Message 有问题。如果我 select 图片是否在上传控制中,我的 webApplication 总是给我警告信息 error happened , your data is not valid 。 但是当我从 MainGoodMetaData.cs 中删除 [Required(ErrorMessage = "select image plz")] 时,它工作正常!

有人能帮帮我吗?非常感谢

MainGoodMetaData.cs

[Required(ErrorMessage = "select image plz")]
[DisplayName("good image")]
[Display(Name = "good image")]
[DataType(System.ComponentModel.DataAnnotations.DataType.ImageUrl)]
public string GoodImage { get; set; }

AddMainGood.cshtml

<div class="form-group">
    <div class="col-md-10">
        @Html.Upload("UploadImage")
        @Html.ValidationMessageFor(model => model.GoodImage)
    </div>
    @Html.LabelFor(model => model.GoodImage, new { @class = "control-label col-md-2" })
  </div>

管理员控制器

 [HttpPost]
public ActionResult AddMainGood(MainGood maingood, HttpPostedFileBase UploadImage)
{
    MainGoodRepositories blMainGood = new MainGoodRepositories();
    string path2 = "";
    var fileName2 = "";
    var rondom2 = "";
    if (UploadImage != null)
    {
        fileName2 = Path.GetFileName(UploadImage.FileName);
        string pic = System.IO.Path.GetFileName(UploadImage.FileName);
        rondom2= Guid.NewGuid() + fileName2;
        path2 = System.IO.Path.Combine(
                              Server.MapPath("~/Images/MainGoods"), rondom2);

        maingood.GoodImage = rondom2;
    }
    if (ModelState.IsValid)
    {
        UploadImage.SaveAs(path2);
        maingood.GoodImage = rondom2;
        if (blMainGood.Add(maingood))
        {
            return JavaScript("alert('added');");
        }
        else
        {
            return JavaScript("alert('didn't add');");
        }
    }
    else
    {
        return JavaScript("alert('error happened , your data is not valid');");
    }
}

UploadHelper.cs

 public static class UploadHelper
 {
 public static MvcHtmlString Upload(this HtmlHelper helper, string name, object htmlAttributes = null)
 {

TagBuilder input = new TagBuilder("input");
input.Attributes.Add("type", "file");
input.Attributes.Add("id", helper.ViewData.TemplateInfo.GetFullHtmlFieldId(name));
input.Attributes.Add("name", helper.ViewData.TemplateInfo.GetFullHtmlFieldName(name));

 if (htmlAttributes != null)
 {
    var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
    input.MergeAttributes(attributes);
 }

return new MvcHtmlString(input.ToString());
}

 public static MvcHtmlString UploadFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, object htmlAttributes = null)
 {

 var data = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
 TagBuilder input = new TagBuilder("input");
 input.Attributes.Add("type", "file");
 input.Attributes.Add("id", helper.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression)));
 input.Attributes.Add("name", helper.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression)));

if (htmlAttributes != null)
{
    var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
    input.MergeAttributes(attributes);
}

return new MvcHtmlString(input.ToString());
</div>

有很多方法可以验证服务器端和客户端的文件输入,这取决于您所处理的情况。例如,如果你想在服务器端进行复杂的验证,你可以创建一个自定义验证属性。但是,如果您只需要使用客户端验证的简单必需文件输入,您应该更改模型:

[Required(ErrorMessage = "Select a file")]
public HttpPostedFileBase GoodImage { get; set; } 

如您所见,我将 GoodImage 属性 更改为 HttpPostedFileBase,然后在您的视图中,我们只需手动添加所需的验证即可:

<div class="form-group">
    <div class="col-md-10">
        <input type="file" data-val="true" data-val-required="please select a file" name="GoodImage" />
        @Html.ValidationMessage("file")
    </div>
    @Html.LabelFor(model => model.GoodImage, new {@class = "control-label col-md-2"})
</div>
<input type="submit" value="Send"/>

以及您的操作方法:

    [HttpPost]
    public ActionResult AddMainGood(MainGood model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }
        string path2 = "";
        var fileName2 = "";
        var rondom2 = "";
        fileName2 = Path.GetFileName(model.GoodImage.FileName);
        string pic = System.IO.Path.GetFileName(model.GoodImage.FileName);
        rondom2 = Guid.NewGuid() + fileName2;
        path2 = System.IO.Path.Combine(
                              Server.MapPath("~/Images/MainGoods"), rondom2);
        // other code
    }