为什么验证消息在asp.net mvc中与上传控件无法正常工作?

时间:2016-01-05 12:05:32

标签: asp.net-mvc validation razor upload asp.net-mvc-5

我在asp.net mvc 5中有一张上传图片表格。

一切都很好,但Validation Error Message存在问题。如果我在上传控件中选择图像,我的webApplication总是会给我提示警告消息error happened , your data is not valid。 但是当我从[Required(ErrorMessage = "select image plz")]删除MainGoodMetaData.cs时,它运行正常!

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

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>

1 个答案:

答案 0 :(得分:1)

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

[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
    }