2015-10-06 42 views
1

我想通過jQuery加載部分視圖並將其加載到頁面中。部分視圖中有一個<img>MVC JQuery加載部分圖像潛在危險請求

這裏是PartialView:

@model NBAPicks.Models.PickedTeamLogoViewModel 

@ViewHelpers.GetTeamLogoForPick(Model.TeamAbbr, Model.GameID, Model.UserName) 

這裏是助手代碼:

public static MvcHtmlString GetTeamLogoForPick(string abbr, int gameID, string userName) 
{ 
    var imagePath = ImageUrl("Team Logos", abbr + ".gif"); 
    var html = "<img src=\"" + imagePath + "\" id=\"" + gameID.ToString() + "_" + userName + "\" class=\"pick-logo\" />"; 
    return new MvcHtmlString(html); 
} 

凡imageURL表示:

private static string ImageUrl(string subFolder, string fileName) 
{ 
    return VirtualPathUtility.ToAbsolute(ImagesDir + "\\" + subFolder + "\\" + fileName); 
} 

這裏是控制器的方法:

[Authorize] 
public JsonResult GetPickedTeamLogo(string teamAbbr, int gameID, string userName) 
{ 
    var viewModel = new PickedTeamLogoViewModel() 
    { 
     TeamAbbr = teamAbbr, 
     GameID = gameID, 
     UserName = userName 
    }; 
    return Json(_partialStringRenderer.RenderRazorViewToString(this, "_PickedTeamLogo", viewModel), JsonRequestBehavior.AllowGet); 
} 

這裏是我加載它在jQuery的:現在

setTimeout(function() { 
    var ajaxRequest = $.ajax({ 
     type: "GET", 
     url: '@Html.Raw(Url.Content("~/Admin/GetPickedTeamLogo/?teamAbbr="))' + teamAbbr + '&gameID=' + gameID + '&userName=' + userName, 
     cache: false, 
     data: { teamAbbr: teamAbbr, gameID: gameID, userName: userName }, 
     async: false, 
     dataType: 'json', 
     error: function() { 
      console.log('failure'); 
      alert('AJAX fail - this is a bug, report it!'); 
     }, 
     success: function (result) { 
      console.log('AJAX call returned successfully'); 
      console.log('result: ' + result); 
      $("#" + userName + "_logo").load(result); // HERE!!! 
     } 
    }); 
}, 0); 

,通過控制檯輸出返回的HTML看起來很好,正確的:

<img src="/Content/Team Logos/MIA.gif" id="1238_tim" class="pick-logo" /> 

但控制檯報告這個錯誤,我嘗試並加載HTML:

GET http://localhost:53441/%3Cimg 400 (Bad Request)

我可以從這裏向下鑽取到這個錯誤:

A potentially dangerous Request.Path value was detected from the client (<).

爲什麼會發生此錯誤,以及如何解決它?

回答

1

其中一個請求字段包含一個<,觸發ASP MVC保護措施,認爲用戶可能會嘗試提交腳本標記或其他內容。

爲了解決這個問題,這個動作過濾器添加到您的GetPickedTeamLogo控制器動作:

[ValidateInput(false)] 

編輯: 對不起,我忘了,你還必須在你的web.config中添加這在

<httpRuntime requestValidationMode="2.0"/> 

EDIT2:

好了,你的問題來自於一個事實,即你的助手返回你,你嘗試作爲一個網址(結果)使用img標籤

你不啃老族調用負載,但只是追加你的形象是這樣的:

$("#" + userName + "_logo").append(result); 
+0

啊,同樣的結果很遺憾。 – Hanshan

+0

將過濾器添加到GetPickedTeamLogo操作後,它是否嚴格輸出相同的錯誤? –

+0

是一樣的。 – Hanshan