asp.net-mvc 将值传递给 ASP.Net MVC3 中 Razor 视图中的 HREF

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5484125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:03:59  来源:igfitidea点击:

Passing value to a HREF in a Razor view in ASP.Net MVC3

asp.net-mvcasp.net-mvc-3razor

提问by SocialCircus

   <a href="@(Html.MyActionHref(controllerName: "MyController", actionName: "MyAction"))">

The above line generates a hyperlink for Razor view. The html helper method MyActionHref() creates the link. On clicking the link it calls an action method from controller. Now suppose the action controller method which this link calls is parameterized i.e.
public ActionResult MyAction(string myParams){}
(The html helper method MyActionHref() is even overloaded to accept three parameters accordingly.)

上面的行生成 Razor 视图的超链接。html 辅助方法 MyActionHref() 创建链接。单击链接时,它会从控制器调用操作方法。现在假设这个链接调用的动作控制器方法是参数化的,即
public ActionResult MyAction(string myParams){}
(html helper 方法 MyActionHref() 甚至被重载以相应地接受三个参数。)

How this additional parameter can be passed to the controller action method from the model?
Say,

如何将此附加参数从模型传递给控制器​​操作方法?
说,

<a href="@(Html.MyActionHref(controllerName: "MyController", actionName: "MyAction",params: new {....} }))">  

Any suggestions?

有什么建议?

回答by Darin Dimitrov

Why are you using such helper when you can simply:

当您可以简单地执行以下操作时,为什么要使用此类帮助程序:

@Html.ActionLink(
    "some text", 
    "MyAction", 
    "MyController", 
    new { myParams = "Hello" }, 
    null
)

which will generate the proper anchor tag:

这将生成正确的锚标记:

 <a href="/MyController/MyAction?myParams=Hello">some text</a>

回答by Mikael ?stberg

You could either use the Url.Actionmethod, or copy its behaviour.

您可以使用该Url.Action方法,也可以复制其行为。

@Url.Action(
   controllerName: "MyController", 
   actionName: "MyAction", 
   routeValues: new { id = 1 }
);

Have a look at the signature of that method to find what you want to do.

查看该方法的签名以找到您想要执行的操作。