【问题标题】:Combining ASP.NET Controller Route with AngularJS object id将 ASP.NET 控制器路由与 AngularJS 对象 ID 相结合
【发布时间】:2018-01-03 11:09:09
【问题描述】:

我有一个使用服务器端 @foreaches 的 ASP.NET 视图,现在已替换为 AngularJS。

现在我使用ng-repeat="record in records",我不再使用@foreach

@record.Id 一起使用的实际代码现在不适用于{{record.id}}

<td class="text-nowrap">
    <a asp-controller="Records" asp-action="Edit" asp-route-id="{{record.id}}">Edit</a>
    <a asp-controller="Records" asp-action="Details" asp-route-id="{{record.id}}">View</a>
    <a asp-controller="Records" asp-action="Delete" asp-route-id="{{record.id}}">Delete</a>
</td>

显然,因为@record.Id 在服务器端...

现在,我看到的解决方案是设置类似

<a href="/Records/Edit/{{record.id}}"></a>

但是,如果控制器的路由发生变化,它可能会导致无处可去...有没有办法解决这个问题?

附言。

更多代码以便更好地理解:

<div ng-app="tablesApp" ng-controller="tablesController as tc">
<table>
  <thead>
    <tr>
      <th>@Html.DisplayNameFor(model => model.Name)</th>
      <th>@Html.DisplayNameFor(model => model.Description)</th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="record in records">
      <td>{{record.name}}</td>
      <td>{{record.description}}</td>
      <td>
        <a asp-controller="Records" asp-action="Edit" asp-route-id="{{record.id}}">Edit</a>
        <a asp-controller="Records" asp-action="Details" asp-route-id="{{record.id}}">View</a>
        <a asp-controller="Records" asp-action="Delete" asp-route-id="{{record.id}}">Delete</a>
      </td>
    </tr>
  </tbody>
</table>
</div>

JS 控制器:

$http.get("/api/Records")
    .then(function (response) {
        tc.records = response.data;
    }));

【问题讨论】:

    标签: c# asp.net angularjs asp.net-core asp.net-core-1.1


    【解决方案1】:

    如果你在 razor 视图中使用 foreach(显然你这样做了),那么你不能使用角度语法 {{record.id}} 你必须使用 @record.id

    但是,如果您在 AngularJs 中以数组/列表的形式获取记录,那么您必须更改您的 html 并使用 ng-repeat

    -- 编辑

    对不起,又看到你的代码了,你使用了asp-actionasp-controller等 它们是核心版本的 TAG HELPERS,换句话说,它们将在服务器端呈现,而您将在浏览器中得到的实际上是锚链接之类的

    &lt;a href="/Records/Edit/{{record.id}}" &gt;Edit&lt;/a&gt;

    如您所知,AngularJs 是客户端,因此不会呈现。要么像你已经做的那样使用@Url.Action,或者你可以删除asp-route-id,然后使用自定义指令添加id。

    【讨论】:

    • 我已经使用ng-repeat="record in records",我不再使用@foreach
    • 那么您能否发布包含ng-repeat 的包装元素?如果您发布包含ng-controller的帖子会更好
    • 假设ng-repeat="record in records" 位于上述代码中的&lt;td&gt; 标记中。它如何改变解决方案?
    • 很多场景,我要求ng-controller 检查是否有重叠,这在 AngularJs 中是不允许的。也许你使用角度路由,也许你根本没有从你的控制器等得到任何结果......无论如何祝你好运:)
    • 谢谢。我添加了你问的代码......我不知道角度路由,在这种情况下有帮助吗?
    【解决方案2】:

    其实硬编码的路由是使用更好一点的选择

    <a href="@Url.Action(action: "Edit", controller: "Records")/{{record.id}}" ></a>
    

    但是这个应该有{ActionRoute}/{id} 固定结构...

    【讨论】:

      猜你喜欢
      • 2013-08-04
      • 2016-12-11
      • 2018-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多