将图像上传的模型状态错误传递给视图

时间:2014-07-25 15:18:32

标签: asp.net asp.net-mvc-4

我需要验证图片上传。我在我的控制器中使用modelstate编写了验证,我需要在我的视图中传递这些验证。 我的观点是

<div id="MemberPicture">  

       @using (Html.BeginForm("UpdateMemberPhotoDetails", "Member",FormMethod.Post, new { enctype = "multipart/form-data" }))
        {
        <b> Pictures  </b>               
            <table>
                <tr>
                    <td>                        

                       <img src= "@Url.Content(Model.ImagePath)" alt="Image" width="200" height="200"/>
                    </td>
                </tr>                     
           <tr>            
                <td>
                    <input type="file" style="width:500px;" name="imgfile" id="file" data-val="true" data-val-required="File is required" />

                </td>
            </tr>
        <tr>
            <td><input type="submit" value="Upload" class="ButtonStyleForProfiles"/></td></tr> 

            </table>               
  }
  </div>

我的控制代码是

public ActionResult UpdateMemberPhotoDetails( HttpPostedFileBase imgfile)
        {
            if (ModelState.IsValid)
            {
                if (imgfile == null)
                {
                    ModelState.AddModelError("File", "Please Upload Your imgfile");                  
                }
                else if (imgfile.ContentLength > 0)
                {
                    int MaxContentLength = 1024 * 1024; //1 MB
                    string[] AllowedFileExtensions = new string[] { ".jpg", ".png" };
                    var fileExtension = imgfile.FileName.Substring(imgfile.FileName.LastIndexOf('.'));
                    if (!AllowedFileExtensions.Contains(fileExtension))
                    {
                        ModelState.AddModelError("File", "Please imgfile of type: " + string.Join(", ", AllowedFileExtensions));
                    }
                    else if (imgfile.ContentLength > MaxContentLength)
                    {
                        ModelState.AddModelError("File", "Your imgfile is too large, maximum allowed size is: " + MaxContentLength + " MB");
                    }
                    else
                    {
                        var folderName = UserDetailsUtil.GetMemberPhotoPathFolderName(SessionData.UserID);
                        var fileName = SessionData.UserID;
                        var path = Path.Combine(Server.MapPath("~/Content/Upload/MemberProfilePhotos/" + folderName), fileName + fileExtension);
                        imgfile.SaveAs(path);
                        ModelState.Clear();
                        ViewBag.Message = "Image uploaded successfully";                       
                    }
                }
            }
            return View();
        }

如何将模型状态错误返回到我的视图中。保存图像后应打印视包消息。有人可以帮助我

1 个答案:

答案 0 :(得分:0)

之后

@using (Html.BeginForm())
    {

写下这一行:

@Html.ValidationSummary(true)

或者您可以执行if语句来显示错误消息:

@if (!ViewData.ModelState.IsValid)
{
//show error
}