如何在ASP.NET Core MVC中为asp标记助手添加链接参数

时间:2016-06-27 06:19:03

标签: c# asp.net-core asp.net-core-mvc url-parameters tag-helpers

我对 ASP.NET MVC 1-5 有很多经验。现在我学习 ASP.NET Core MVC 并且必须将参数传递给页面中的链接。例如,我有以下 Action

 [HttpGet]
 public ActionResult GetProduct(string id)
 {
      ViewBag.CaseId = id;
      return View();
 }

如何使用代码帮助程序实现此操作的链接?

<a asp-controller="Product" asp-action="GetProduct">ProductName</a>

4 个答案:

答案 0 :(得分:142)

您可以使用属性前缀asp-route-作为路径变量名称的前缀。

示例:

<a asp-controller="Product" asp-action="GetProduct" asp-route-id="10"> ProductName</a>

答案 1 :(得分:5)

您可能要应用以下语法。

<a asp-controller="Member"
   asp-action="Edit"
   asp-route-level="3"
   asp-route-type="full"
   asp-route-id="12">Click me</a>

这将产生这样的呼叫路由。

  

/会员/编辑/ 3 /完整/ 12

然后您可以通过如下所示的方法接收它。

[Route({level}/{type}/{id})]
public IActionResult Edit(int level, string type, int id) { ... }

尽管在MVC中不需要装饰该方法的属性,但它可以更清楚地显示如何将链接中的属性绑定到方法中传递的参数。

答案 2 :(得分:0)

在后端:

这段代码必须写在控制器中动作的顶部

[Route("/Controller/Method/{Object or varible name}")]
public actionresult method name(your variable)
{
    //your code...
}

在前端:

@{
var url = "/Controller/Method/" + your data;
<a href="@url"> click me for send data()</a>
}

答案 3 :(得分:-1)

如果要将变量id放入网格或表中的链接中,可以使用下面的代码

Invalid NEST response built from a unsuccessful low level call on POST: /situationsindex/searchablesituation/_search?typed_keys=true # Audit trail of this API call: - [1] BadResponse: Node: http://localhost:9200/ Took: 00:00:00.0030001 # OriginalException: System.Net.WebException: The remote server returned an error: (400) Bad Request. at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult) at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Elasticsearch.Net.HttpConnection.d__14`1.MoveNext() in C:\Users\russ\source\elasticsearch-net-master\src\Elasticsearch.Net\Connection\HttpConnection.cs:line 242 # Request: # Response: