Return 未选择图像时到同一视图

Return to the same view when no image is selected

我有一个上传控件。但是,如果用户没有 select 图片并按下上传按钮,用户将收到一条消息,提示 he/she 必须返回并重试,如下所示:

if (isSavedSuccessfully)
            {
                return Redirect(Url.Action("Edit", "Account") + "#tabs-2");
            }
            else
            {
                return Json(new { Message = "Error in saving file, Go back and  try again" });
            }

但这当然不是你想要的。因为消息在单独的视图中,而不是在您可以上传图像的视图中。但是如何在上传图片的同一视图中显示消息?

这是我的完整方法:

[HttpPost]
        public ActionResult EditPhotos(UserProfile user, HttpPostedFileBase file)
        {            
            bool isSavedSuccessfully = true;
            try
            {

                if (file != null || file.ContentLength > 0)
                {
                    if (IsImage(file) == false)
                    {
                        // Invalid file type
                        return Json(new { Message = "Error in saving file, Go back and  try again" });
                    }
                    int iFileSize = file.ContentLength;
                    if (iFileSize > 3048576)  // 1MB
                    {
                        // File exceeds the file maximum size
                        return Json(new { Message = "Image is to large , Go back and  try again" });
                    }                   
                }

                if (ModelState.IsValid)
                {
                    var job = new ImageJob(file, "~/Images/profile/<guid>", new Instructions("mode=max;format=jpg;width=400;height=400;"));
                    job.CreateParentDirectory = true;
                    job.AddFileExtension = true;
                    job.Build();

                    var DirSeparator = Path.DirectorySeparatorChar;
                    var fileName = Path.GetFileName(job.FinalPath);

                    if (ModelState.IsValid)
                    {
                        string username = User.Identity.Name;                        
                        user = db.userProfiles.FirstOrDefault(u => u.UserName.Equals(username));
                        user.Image = new byte[file.ContentLength];
                        file.InputStream.Read(user.Image, 0, file.ContentLength);
                    }
                    // Update fields                
                    user.ImageMimeType = file.ContentType;
                    db.Entry(user).State = EntityState.Modified;
                    db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                isSavedSuccessfully = false;

            }

            if (isSavedSuccessfully)
            {
                return Redirect(Url.Action("Edit", "Account") + "#tabs-2");
            }
            else
            {
                return Json(new { Message = "Error in saving file, Go back and  try again" });
            }

        }

这是我对上传图片的看法:

@model ContosoUniversity.Models.UserProfile
@using ContosoUniversity.Source
@{
    ViewBag.Title = "Edit";
}
<div id="tabs-2">
    @using (Html.BeginForm("EditPhotos", "Account", FormMethod.Post, new { id = "form_Id", enctype = "multipart/form-data" }))
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">
            <h4>Profile Photo</h4>
            <hr />

            @Html.HiddenFor(model => model.Id)

            <div id="upload-choices">
                <div class="editor-label">
                    @Html.ValidationMessageFor(model => model.Image)
                </div>
                <div class="editor-row">
                    @Html.ValidationSummary(true)
                </div>
            </div>
            <br />
            Upload an profile image not bigger then 3 MB
            <table class="table">
                <tr>
                    @if (Model.Image == null)
                    {
                        <th><img class="pull-left" src="~/Images/RockOnBycicle.png" width="200" height="150" alt="RockCycle" /></th>

                    }
                    else
                    {
                        <th><img width="200" height="150" src="@Url.Action("GetImage", "Account", new { id =  Model.Id })"></th>

                    }
                </tr>
            </table>
            <input type="file" name="file" class="filestyle" data-icon="false">
            <br />
            <div class="progress progress-striped">
                <div class="progress-bar progress-bar-success">0%</div>
            </div>

            <div id="status"></div>
            <br />          
            <div class="pull-left">
                <div class="col-md-offset-0">
                    <input type="submit" value="Upload" accept="image/x-png, image/gif, image/jpeg" class="btn btn-default pull-left" />

                </div>
            </div>

        </div>
    }

    <br /><br /><br />
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>

</div>

@section Scripts
{
    <link href="@Url.Content("~/Content/themes/base/jquery-ui.css")" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.11.0.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.form.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery-ui-1.10.4.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/bootstrap-filestyle.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.form.min.js")" type="text/javascript"></script>

    <script type="text/javascript">
    </script>
}

谢谢

添加 ModelState 错误和 return 视图(否则重定向),例如

if (isSavedSuccessfully)
{
    return Redirect(Url.Action("Edit", "Account") + "#tabs-2");
}
else
{
    ModelState.AddModelError("Image", "your message");
    return View(user);
}