MVC View作为复杂JsonResult的一部分

时间:2015-08-06 07:25:12

标签: javascript .net json asp.net-mvc angularjs

从MVC后端请求视图时,我希望收到的信息不仅仅是查看内容:

public class CustomJsonViewResult
{
    public string Subject { get; set; }

    public ActionResult View { get; set; }
}

随着时间的推移,上述课程会变得更加复杂。

这将在Controller方法中创建,如下所示:

public JsonResult Person()
{
    return Json(new CustomJsonViewResult
    {
        View = View(),
        Subject = "Update an existing person"
    }, JsonRequestBehavior.AllowGet);
}

会添加BL逻辑来确定主题,而不是现在的静态值。

在接收客户端上,我有一个AngularJS指令,其链接如下:

link: function (scope, element, attrs) {
    screensService.GetPartialView(attrs.view).then(function (viewData) {

        var linkFunc = $compile(viewData.View);
        var content = linkFunc(scope);
        element.append(content);
    });
}

当我直接返回ActionResult时,这是有效的,但在当前设置中,我收到此错误:

typeError: Cannot read property 'ownerDocument' of undefined
    at Function.Sizzle.contains (jquery-2.1.4.js:1430)
    at Function.jQuery.extend.buildFragment (jquery-2.1.4.js:5147)
    at jQuery.fn.extend.domManip (jquery-2.1.4.js:5387)
    at jQuery.fn.extend.append (jquery-2.1.4.js:5218)
    at PartialViewLoaderDirective.js:27
    at processQueue (angular.js:14569)
    at angular.js:14585
    at Scope.$get.Scope.$eval (angular.js:15848)
    at Scope.$get.Scope.$digest (angular.js:15659)
    at Scope.$get.Scope.$apply (angular.js:15953)

如果我将viewData记录到控制台,我会得到:

Object {Subject: "Update an existing person", View: Object}
    Subject: "Update an existing person"
    View: Object
    MasterName: ""
    Model: null
    TempData: Array[0]
    View: null
    ViewBag: Object
    ViewData: Array[0]
    ViewEngineCollection: Array[2]
    ViewName: ""
    jQuery21400306884015444666152: 19
    __proto__: Object
    __proto__: Object

摘要

知道原因是什么无法读取属性' ownerDocument'未定义的错误?据我所知,一切都按预期可用。

1 个答案:

答案 0 :(得分:0)

我使用Url方法开始工作:

public ActionResult Person()
{
    return View();
}

public JsonResult PersonAsJson()
{
    return Json(new CustomJsonViewResult
    {
        Url = Url.Action("Person"),
        Subject = "Update an existing person"
    }, JsonRequestBehavior.AllowGet);
}

然后在客户端:

screensService.GetPartialView(attrs.view).then(function (viewData) {
    $.post(viewData.Url, function (view) {
        var linkFunc = $compile(view);
        var content = linkFunc(scope);
        element.append(content);
    });
});

RenderRazorViewToString不起作用,因为编译器找不到ViewData.Model(Resharper也没有)。

RenderView不起作用,因为我无法将ViewResult提供给ViewContext。

谢谢!