简体   繁体   English

Ajax postback partialview没有加载更新的图像

[英]Ajax postback partialview not getting loaded with updated image

I am trying to create a sample MVC4 webpage with partialViews 我正在尝试使用partialViews创建一个示例MVC4网页

on my parent page ,eg., Index.cshtml page I am displaying a partialView page which will allow the user to view/update profile photo 在我的父页面上,例如,Index.cshtml页面我正在显示一个partialView页面,允许用户查看/更新个人资料照片

When the index page loads ,I need this partial page to show up the photo if photo is available 加载索引页面时,如果照片可用,我需要此部分页面显示照片

once the page is loaded ,when the user uploads a new photo,I need only the partialView page to do an ajax postback and show up the new photo . 一旦页面加载,当用户上传新照片时,我只需要partialView页面进行ajax回发并显示新照片。

I am able to load the page with photo fetched from DB, I am able to Save new photo to db by clicking "#btnPhotoUpload" button. 我可以加载带有从DB获取的照片的页面,我可以通过单击“#btnPhotoUpload”按钮将新照片保存到数据库。 But after saving the photo ,the partialview is not getting refreshed automatically.Please help me how to get my partialview page to refesh and display the updated photo. 但保存照片后,部分视图不会自动刷新。请帮助我如何让我的部分视图页面重新显示并显示更新的照片。

Here is my index page ie., "Index.cshtml" 这是我的索引页面,即“Index.cshtml”

@model MvcSamples.Models.ViewModels.UserInfoViewModel
@{

    ViewBag.Title = "Ajax Partial Postback demo";
    ViewBag.UserId = 1;
}

<h2>PersonalInfo example</h2>
<div id="photoForm">
    @Html.Partial("_UserPhoto")
</div>
<div id="OtherDetails">
    @Html.Partial("_UserDetails")
</div>

Here is my PartialView, ie _UserPhoto.cshtml 这是我的PartialView,即_UserPhoto.cshtml

@model MvcSamples.Models.ViewModels.UserInfoViewModel
@using (Ajax.BeginForm("SaveProfilePhoto", "Example", new { id = "1" }, new AjaxOptions { UpdateTargetId = "photoForm", OnSuccess = "onSuccess" }, new { encType = "multipart/form-data" }))
{ 
    @Html.AntiForgeryToken() 
    @Html.ValidationSummary(true) 
    <a>
        <img id="imgPhoto"  width="100px" height="100px"/>
        <label for="photo">Photo:</label>
        <input type="file" name="photo" id="photo" />
      <input id="btnPhotoUpload" type="button" value="Apply" />
    </a>

    <script type="text/javascript">
        $(document).ready(function () {

            $("#imgPhoto").attr('src', "@Url.Action("GetProfileImage", "Example", new { id = ViewBag.UserId })");

            $("#btnPhotoUpload").click(function (event) {
                //on-click code goes in here.
                event.preventDefault();
                SavePhotoToDb();

            });

            function SavePhotoToDb() {
                var json;
                var data;
                $.ajax({
                    type: "POST",
                    url: "/Example/SaveProfilePhoto",
                    data: new FormData($("#form0").get(0)),
                    dataType: "html",
                    contentType: false,
                    processData: false,
                    success: saveItemCompleted(data),
                    error: saveItemFailed
                });
            }

            function saveItemCompleted(data) {
                    $("#photoForm").html(data);
        }

        function saveItemFailed(request, status, error) {
            }
        });
    </script>
}

Here is my controller ExampleController: 这是我的控制器ExampleController:

namespace MvcSamples.Controllers
{
    public class ExampleController : Controller
    {
        IUserDetails usr = new UserDetails();

        // GET: /Example/
        [HttpGet]
        public ActionResult Index()
        {
            //usr.GetProfilePhoto(WebSecurity.GetUserId(User.Identity.Name));
            if (!string.IsNullOrWhiteSpace(User.Identity.Name))
            {
                ViewBag.UserId = WebSecurity.GetUserId(User.Identity.Name);
            }

            UserInfoViewModel model = new UserInfoViewModel();
            model.GenderList = usr.FillGenderTypesDropDownList();
            return View(model);
        }


        [HttpPost]
        public ActionResult SaveProfilePhoto(HttpPostedFileBase photo, UserInfoViewModel model)
        {
            string path = @"C:\Temp\";
            if (photo != null)
            {
                model.UserId = 1;//WebSecurity.GetUserId(User.Identity.Name);
                ViewBag.UserId = model.UserId;
                var binary = new byte[photo.ContentLength];
                photo.InputStream.Read(binary, 0, photo.ContentLength);
                UserPicModel upModel = new UserPicModel();
                upModel.UserPhoto = binary;
                upModel.UserId = model.UserId;
                usr.InsertProfilePhoto(upModel);

            }

            return PartialView("_UserPhoto", model); 
        }

        public FileResult GetProfileImage(int id)
        {
            byte[] barrImg = usr.GetProfilePhoto(id);
            return File(barrImg, "image/png");
        }

    }
}

Update: 更新:

As @David Tansey suggested ,I added code to refresh image inside SaveCompleted(data). 正如@David Tansey建议的那样,我添加了代码来刷新SaveCompleted(数据)中的图像。

function RefreshImage() {
    $("#imgPhoto").attr('src', function () {
        // the datetime portion appended to the url avoids caching issues
        // and ensures that a fresh image will be loaded every time
        var d = new Date();

        return this.src + '?' + d.getTime();
    });
}

But the above code is refreshing the image only after I click the upload button twice . 但是上面的代码只有在我单击上传按钮两次后才刷新图像。 Actually I need this to refresh the image immediately after the $("#btnPhotoUpload").click . 实际上我需要在$("#btnPhotoUpload").click之后立即刷新图像$("#btnPhotoUpload").click Any suggestions? 有什么建议么?

I also tried disabling cache at the controller but no luck: 我也尝试在控制器上禁用缓存,但没有运气:

[OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)]

I am pretty sure the problem is that the browser is caching the image file and does not 'perceive' the need to bring it across the wire again after you upload a new one. 我很确定问题是浏览器正在缓存图像文件,并且在您上传新文件后不会“感知”需要再将其带到网上。

Look at the following post for a description of how to attach a dummy (yet dynamic) query string value to prevent the caching from occuring. 请查看以下帖子,了解如何附加虚拟(但动态)查询字符串值以防止缓存发生。 I think this approach will solve your problem. 我认为这种方法可以解决您的问题。

asp.net mvc jquery filling image asp.net mvc jquery填充图片

Hope that helps. 希望有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM