从jQuery中的MVC ViewData中检索URL
用这个苦苦挣扎。我将控制器的绝对URL传递给View,并试图检索jquery中的URL,将它传递给Ajax调用。该URL没有正确构建。任何帮助如何以正确的方式检索它?从jQuery中的MVC ViewData中检索URL
我试了@ Html.Raw在这里。但没有运气!
MVC控制器
public IActionResult Something()
{
var baseDirPath= System.AppDomain.CurrentDomain.BaseDirectory;
var fileLocation = Path.Combine(baseDirPath, "wwwroot", "myDir",
"test.docx");
ViewData["Path"] = fileLocation;
return View();
}
MVC视图
<script type="text/javascript">
$(document).ready(function() {
//Cannotretrieve the path here from the viewdata
var path = "@Html.Raw(ViewData["Path"])";
console.log(documentPath);
var kkk= $("#div");
kkk.kendoWindow({
open: function (e) {
$.ajax({
url: documentPath,
async: true,
success: function (msg) {
//success
},
});
}
}).data("kendoWindow").center().open();
});
</script>
if your view is razor:
var str = @Html.Raw(Json.Encode(ViewData["Path"]));
,或者如果它的Web表单,使用JavaScriptSerializer(和进口theproper命名空间WebForm中后 - System.Web.Script。序列号):
var str = <%= new JavaScriptSerializer().Serialize(ViewData["Path"])) %>;
in MVC application. Use view models and strongly typed views so that your code looks like this:
var str = <%= new JavaScriptSerializer().Serialize(Model.Path) %>;
This technique is even cooler as now you can JSON serialize the entire view model:
var model = <%= new JavaScriptSerializer().Serialize(Model) %>;
var str = model.Path;
谢谢sd.n.我正在使用剃刀。但是我无法解析Json.Encode中的'Encode'。我正在使用MVC6 – aspnetbeginner245
@ aspnetbeginner245 - MVC 6已被重命名为MVC Core。如果您需要相关答案,您应该为您的问题添加正确的标签。 – NightOwl888
您可以在jQuery中使用ViewData.Eval()
与Html.Encode()
var path = '@Html.Encode(ViewData.Eval("Path"))';
console.log(path);
可以显示示例路径,这是什么路? –
更新的控制器代码 – aspnetbeginner245
您无法使用绝对路径访问该文件,您需要使用相对路径 –