簡體   English   中英

在 HttpPostedFileBase 中使用 RegularExpression 進行圖像驗證在 ModelState.IsValid 中始終為 false

[英]Image validation using RegularExpression in HttpPostedFileBase always false in ModelState.IsValid

我有一個使用 htmlhelper 上傳圖像字段的表單,但在控制器中它總是使用 ModelState.IsValid 返回 false,我不知道我的代碼有什么問題。 你能幫助我嗎? 這是我的代碼。

表單.cshtml

@using (Html.BeginForm("AddonSaveLayout", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    @Html.HiddenFor(x => x.AddonLayoutForm.AddonSetup.Id)
    <div class="box box-primary">
        <div class="box-body">
            <div class="form-group">
                <label>Upload Image </label>
                @Html.TextBoxFor(x => x.AddonLayoutForm.AddonSetup.ImagePath, new { type = "file", @accept = "image/jpg, image/jpeg, image/png" })
                @Html.ValidationMessageFor(model => model.AddonLayoutForm.AddonSetup.ImagePath, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="box-footer">
            @Html.ActionLink("Back", "AddonSetup", null, new { @class = "btn btn-warning" })
            <button type="submit" class="btn btn-primary" id="submitAddCatBtn">Save</button>
        </div>
    </div>
}

模型.cs

 [Required(ErrorMessage = "Please select file.")]
 [RegularExpression(@"([a-zA-Z0-9\s_\\.\-:])+(.png|.jpg|.jpeg)$", ErrorMessage = "Only Image files allowed and should be 5MB or lower.")]
 public HttpPostedFileBase ImagePath { get; set; }

控制器.cs

if (!ModelState.IsValid)
{
    string messages = string.Join("; ", ModelState.Values
                                    .SelectMany(x => x.Errors)
                                    .Select(x => x.ErrorMessage));

     var TicketDesc = db.TicketDescriptions.ToList();
     model.AddonLayoutForm.TicketDescriptions = TicketDesc;
     return View("AddonForm", model);
}

您會收到什么具體錯誤,如果您調試您的方法,模型狀態會告訴您為什么它確定模型無效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM