0

partialViews を使用してサンプル MVC4 Web ページを作成しようとしています

私の親ページ、例えばIndex.cshtmlページで、ユーザーがプロフィール写真を表示/更新できるpartialViewページを表示しています

インデックス ページが読み込まれると、写真が利用可能な場合に写真を表示するには、この部分ページが必要です

ページが読み込まれると、ユーザーが新しい写真をアップロードすると、ajax ポストバックを実行して新しい写真を表示するには、partialView ページのみが必要です。

DB から取得した写真を含むページをロードできます。「#btnPhotoUpload」ボタンをクリックして、新しい写真を db に保存できます。 しかし、写真を保存した後、部分ビューが自動的に更新されません。部分ビュー ページを更新して更新された写真を表示する方法を教えてください。

これが私のインデックスページ、つまり「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>

ここに私の 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>
}

これが私のコントローラーの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");
        }

    }
}

アップデート:

@David Tanseyが提案したように、SaveCompleted(data) 内の画像を更新するコードを追加しました。

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();
    });
}

しかし、上記のコードは、アップロード ボタンを 2 回クリックした後にのみ画像を更新しています。実際には、の直後に画像を更新するためにこれが必要$("#btnPhotoUpload").clickです。助言がありますか?

また、コントローラーでキャッシュを無効にしようとしましたが、うまくいきませんでした:

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

1 に答える 1

2

問題は、ブラウザが画像ファイルをキャッシュしており、新しいファイルをアップロードした後、再度ネットワーク経由で画像を送信する必要があることを「認識」していないことだと確信しています。

ダミーの (ただし動的な) クエリ文字列値をアタッチしてキャッシュが発生しないようにする方法については、次の投稿を参照してください。このアプローチがあなたの問題を解決すると思います。

asp.net mvc jquery 塗りつぶし画像

それが役立つことを願っています。

于 2013-08-07T19:08:11.257 に答える