【问题标题】:Problem preventing evaluation of AngularJS expression when bound with ng-model与 ng-model 绑定时阻止评估 AngularJS 表达式的问题
【发布时间】:2023-11-15 15:33:01
【问题描述】:

我对使用 ASP.NET MVC (5.2.3) 剃须刀引擎呈现但也使用 AngularJS (1.7.4) 的网页有疑问。问题是 AngularJS 正在评估应该呈现为纯文本的内容。

因此,例如,在我们的模型中,我们有一个属性 Name,当其值为 {{1 + 1}} 时,将显示为 2,即正在评估 AngularJS 表达式:

(已编辑的)cshtml 页面如下所示:

@model Models.SomeViewModel

<div ng-controller="RuleController" ng-form="ruleForm" novalidate>
  <!-- stuff here -->
   <div class="panel">
      <div class="panel-heading">
       <!-- stuff here -->
      </div>
    <div class="panel-body ng-cloak">
        <!-- stuff here -->
        <div class="row form-group">
            @Html.LabelFor(model => model.Name, new HtmlAttributeBuilder().WithCssClass("col-sm-1  control-label"))
            <div class="col-xs-12 col-sm-10 col-md-11 pull-right">
                @Html.TextBoxFor(model => model.Name, new HtmlAttributeBuilder().WithCssClass("form-control form-group-margin").WithNgModel("viewModel.name").WithNgChange("updateName(viewModel.name)").WithRequired())
                <span id="name-error" class="text-danger error-text" ng-model="errors.viewModel.Name">{{errors.viewModel.Name}}</span>
            </div>
        </div>

Razor 视图中引用的 C# 类 - HtmlBuilder - 继承自 `Dictionary'

[Serializable]
public class HtmlAttributeBuilder : Dictionary<string, object>
{
    public HtmlAttributeBuilder WithCssClass(string cssClassName)
    {
        this.Add("class", cssClassName);
        return this;
    }

    public HtmlAttributeBuilder WithNgModel(string property)
    {
        this.Add("ng-model", property);
        return this;
    }

    public HtmlAttributeBuilder WithNgChange(string val)
    {
        this.Add("ng-change", val);
        return this;
    }
}

有趣的是,当我查看RuleController$scope.viewModel.name 的值时,我可以看到它是{{1 + 1}}不是 2。

我尝试过使用ng-non-bindable,虽然它阻止了对 Angular 表达式的评估,但它也阻止了对值的持久更新,因为它删除了双向绑定。

【问题讨论】:

  • Angular 文档特别提到不要混合服务器和客户端模板,但我猜你已经将 Angular 添加到现有应用程序中......
  • @Erlend 你能指出我在 AngularJS 文档中的相关部分吗?那真的很有帮助。我不确定为什么要像多年前那样决定混合客户端和服务器端渲染。
  • 在沙盒移除下查看一半:docs.angularjs.org/guide/security
  • @Erlend 谢谢。

标签: c# angularjs asp.net-mvc xss


【解决方案1】:

你试过这个指令吗?

https://docs.angularjs.org/api/ng/directive/ngNonBindable

注意,这可能应该进入 cmets,但我没有足够的声誉。

【讨论】:

  • 谢谢。我也尝试过使用ng-non-bindable。请查看我更新的问题。