2016-06-08 44 views
1

我在我的.Net MVC應用程序中有一個帶有JsonResult操作的「本地化」控制器。Ajax沒有運行Rotativa ViewAsPdf

[HttpGet] 
public ActionResult Index(string id) 
{ 
    var data = JsonConvert.DeserializeObject("\"" + ResourceHelper.GetString(id) + "\""); 

    return Json(data, JsonRequestBehavior.AllowGet); 
} 

此控制器從資源文件中獲取特定資源字符串並將其作爲Json返回。

我創建了一個基於wkhtmltopdf的nuget包「Rotativa」版本1.7.1的pdf。我可以創建PDF,這不是問題。問題來了,當我使用這個PDF瀏覽,這使得Ajax調用到本地化控制器abve JS-文件.. 我的js的PDF查看:

var dataValues = ""; 
$.getJSON("/Localization/Index/" + "resourceStringXY", function (data) { 
    dataValues = data; 
    myFunction(); 
}); 

我Rotativa全文控制器:

return new ViewAsPdf("PdfView", model) 
{ 
    FileName = "PdfName.pdf", 
    PageMargins = new Margins(15, 20, 15, 0), 
    IsJavaScriptDisabled = false, 
    CustomSwitches = cs 
}; 

不知何故,JS Ajax調用無法進行,即使我用wkhtmltopf customswitch選項

「--no一站式慢腳本」

「--javascript延遲25000」

當我只是返回查看視圖,我得到沒有任何問題的Ajax數據。我沒有得到一個JS錯誤或類似的東西。在我的Js上使用Pdf視圖而不是Ajax可能有任何可能性來獲取.Net資源?

THX幫助:)

回答

1

好像Rotativa不支持Ajax調用。由於該網站由Rotativa處理,而不是瀏覽器或其他東西,因此無法解決此問題。這也是爲什麼你的瀏覽器控制檯沒有顯示js錯誤的原因。

我在這裏看到兩個解決方案給你。

  • 生成PDF不同
  • 序列化您的所有字符串成JSON字符串,並把它放到HTML。從那裏使用JavaScript再次閱讀。

你可以寫這樣的助手類。

public class TranslationStrings 
{ 
    public Dictionary<string, string> Strings { get; set; } 

    public TranslationStrings() 
    { 
     //init translation dictionary in constructor 
     Strings = new Dictionary<string, string> 
     { 
      //All the keys you need 
      {"resourceStringXY" , Resources.General.resourceStringXY}, 
      {"resourceStringAB" , Resources.General.resourceStringAB} 
     }; 
    } 

    //simple Method to serialize the dictionary. 
    public string GetJsonString() 
    { 
     JavaScriptSerializer js = new JavaScriptSerializer(); 
     return js.Serialize(Strings); 
    } 
} 

然後,你可以簡單地把JSON字符串放在ViewBag中,像這樣。

ViewBag.translations = new TranslationStrings().GetJsonString(); 

在cshtml視圖中,您可以將它寫入JavaScript變量中。我把它保存爲一個窗口的孩子,所以它全局可訪問你的JavaScript。

<script type="text/javascript"> 
    window.translations = @(Html.Raw(ViewBag.translations)); 
</script> 

比你應該可以訪問這樣的字符串。

window.translations["resourceStringXY"]