从jQuery中的MVC ViewData中检索URL

时间:2017-06-13 19:20:44

标签: jquery asp.net asp.net-mvc asp.net-mvc-4 razor

稍微苦苦挣扎。我将一个绝对URL从控制器传递给View并尝试检索jquery中的URL以将其传递给Ajax调用。网址不构建正确。有关如何以正确的方式检索它的任何帮助吗?

我在这里试过@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>

2 个答案:

答案 0 :(得分:0)

if your view is razor:

var str = @Html.Raw(Json.Encode(ViewData["Path"]));

或者如果是web表单,使用JavaScriptSerializer(以及在将.perper命名空间导入webform后 - System.Web.Script.Serialization):

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;

答案 1 :(得分:0)

您可以在jquery

中使用ViewData.Eval()Html.Encode()
var path = '@Html.Encode(ViewData.Eval("Path"))';
console.log(path);