【问题标题】:Html.RenderAction with AngularHtml.RenderAction 与 Angular
【发布时间】:2019-02-28 14:06:29
【问题描述】:

我试着写下类似的东西;

Html.RenderAction("Reviews", "Poetry", new { id = "{{ poetry.ID }}" });

但它给出了一个错误,例如“参数字典包含方法'System.Web.Mvc.PartialViewResult'的不可空类型'System.Int32'的参数'id'的空条目”

但如果我写下类似下面的内容,它就可以正常工作;

var url = Url.Action("Reviews", "Poetry", new { id = "{{ poetry.ID }}" });

如何在 Html.RenderAction 方法中传递角度值?

【问题讨论】:

    标签: asp.net-mvc angular renderaction


    【解决方案1】:

    假设你有这样的控制器动作:

    public class PoetryController : Controller
    {
        public PartialViewResult Reviews(int id)
        {
            // do something
        }
    }
    

    RenderAction 方法在发送到客户端浏览器之前从服务器解析和渲染,因此您的第一种方法是不可能,因为像 {{ poetry.ID }} 这样的 Angular 表达式无法被服务器端正确解析代码作为动作参数,因此它作为 null 传递并抛出不可为 null 的参数异常,因为 id 声明为 int,而不是 Nullable<int>

    假设你想使用Angular值(或JS值)加载部分视图,通常在控制器内部使用$http()函数,然后调用包含HTTP请求的函数名称:

    Razor 中的 JS 变量

    var pageUrl = '@Url.Action("Reviews", "Poetry")';
    

    角函数

    $http({
        method: 'GET',
        url: pageUrl,
        params: {
            id: poetry.ID
        }).then(function (response) {
            // load partial view here
            angular.element('#targetElement').html(response);
        });
    

    或者使用简写的$http.get(),因为RenderAction 需要 GET 方法来呈现部分视图内容:

    $http.get(pageUrl + '?id=' + poetry.ID).then(function (response) {
        // load partial view here
        angular.element('#targetElement').html(response);
    });
    

    【讨论】:

      猜你喜欢
      • 2011-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-14
      相关资源
      最近更新 更多