未选择图像时返回相同视图

时间:2015-06-14 09:26:26

标签: asp.net-mvc-4 razor json.net entity-framework-5 c#-5.0

我有一个上传控件。但是,如果用户没有选择图像并按下上传按钮,用户将收到一条消息,他/她必须返回并重试,如下所示:

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

谢谢

1 个答案:

答案 0 :(得分:1)

添加ModelState错误并返回视图(否则重定向),例如

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