Изменение изображения src через MVC 3 Action - PullRequest
0 голосов
/ 22 февраля 2012

У меня есть страница с тегом изображения.Изображение, отображаемое тегом изображения, изменяется в зависимости от выбора изображения, сделанного во всплывающем окне.Ниже приведены шаги по воспроизведению моих проблем:

 1. Click button on Main Page and display popup with selectable images
 2. Click any one image in popup to create selection
 3. Click "Associate" button in popup to begin association process
     a. JQuery.post is called to "Associate" selected image to image in Main page
        i. Code in the Controller is run and save the association in the database.
     b. Upon success, the "success" function of the JQuery.post makes a call to an existing javascript function.
        i. This function creates a string in the following format: "{Controller}/{Action}/{PrimaryId}/{SecondaryId}"
        ii. In the function, the "src" of the image in the main page is set to the string created above.
        iii. The change in "src" makes the code in the controller run which in turn returns the specified image.
        iv. The popup is closed

Для всех практических целей код работает, за исключением раздражающей проблемы, заключающейся в том, что независимо от браузера изображение не обновляется при возврате из контроллера черезописанный выше процесс (во время функции JQuery.post "Success").

Следует отметить, что если шаги "bi" - "b.iv" выполняются без "JQuery.post" (т.е.просто извлекая данные изображения, не связываясь сначала), изображение обновляется каждый раз.Используемый код приведен ниже (отредактировано - элементы в фигурных скобках являются заполнителями)

ИЗМЕНЕНО ИЗОБРАЖЕНИЯ

<div id="divMenuItemMedia">
   <img id="imgMenuItemMedia" alt='someAlt' src='/{Controller}/{Action}/{InitialImageId}' />
</div>

КНОПКА, ЧТОБЫ ПОДКЛЮЧИТЬ POPUP

<input type="button" id="btnModifyImage" name="btnModifyImage" class="t-button" value="Change Image" onclick="showImageChooser();" />

ФУНКЦИИ JAVASCRIPT

ГЛАВНАЯ СТРАНИЦА

function GetCurrentMediaItemsByIds(pId, iId) {
        //$('#imgMenuItemMedia').load(function () {
            //alert("Image updated");
       // });
        var imgMedia = document.getElementById("imgMenuItemMedia");
        var sourceUrl = '/{Controller}/{Action}/{pId}/{iId}';
        //$('#imgMenuItemMedia').attr("src", sourceUrl);
        imgMedia.src = sourceUrl;
        InImageSelectionMode = false;
    }

function showImageChooser() {
        var url = '{Controller}/{DataGetterActionForPopup}';
        ShowPopup(url, "#MediaChooserDialog", null);
    }

POPUP

function associateMediaSelection(e) {
   // The entity name is saved in hidden field in the "Edit" page
   var entityName = document.getElementById("hidEntityName").value;
   var contentPath = entityName + "/Associate" + entityName + "ToMediaItem";
   var url = '{Controller}/{Action}';
   var primaryId = {pId};
   var secondaryId = {sId};
   var entityId = {eId};
   var data = { "entityId" : eId, "primaryId": pId, "secondaryId": sId };

   var jqxhr = $.post(url, data, function (e) {
                GetCurrentMediaItemsByIds(presentationId, document.getElementById("hid" + entityName + "Id").value);

                closeMediaSelection();
            });
        }
function closeMediaSelection()
        {
            var windowPopup = $("#MediaChooserDialog").data('tWindow');
            windowPopup.close();
        }

Кто-нибудь имеет представление о том, что может препятствовать обновлению изображения?

1 Ответ

1 голос
/ 22 февраля 2012

Я предполагаю, что это полный, настоящий код. В этом случае:

var sourceUrl = '/{Controller}/{Action}/{pId}/{iId}';

будет проблемой, так как это ничего не значит в javaascript. Вы можете вставить:

var sourceUrl = '@Url.Action("Action","Controller")'

где Action и Controller заполнены именами вашего контроллера / метода действия.

...