简体   繁体   English

@ Url.Action(“ Action”,“ Controller”)调用具有相同名称的post和get方法

[英]@Url.Action(“Action”,“Controller”) calls both post and get method with same name

I have a controller where there are two action methods with same name with HttpPost and HttpGet as shown below , when link with @Url.Action("DoSomething","Controller") is called then both the method are invoked , how do I call only GET method? 我有一个控制器,其中有两个同名的HttpPost和HttpGet动作方法,如下所示,当@Url.Action("DoSomething","Controller")链接时,两个方法都被调用,我该如何调用只有GET方法?

Is there anyway to pass type GET or POST in @URL.Action or any other way? 无论如何,可以通过@URL.Action或其他方式传递GET或POST类型?

[HttpGet]
public ActionResult DoSomething(int ? MyParam)
{

}

[HttpPost]
public ActionResult DoSomething(MyModel Model)
{

}

In Razor View When I build a link like 在Razor View中建立链接时

<a href="@Url.Action("DoSomething","Home",new { MyParam= Whatever})">JustDoIt</a>

Then it calls both POST and GET methods, even after specifiying parameter as int and not the model 然后,即使将参数指定为int而不是模型,它也会调用POST和GET方法

Try adding post in the form declaration: 尝试在表单声明中添加post:

@using (Html.BeginForm("DoSomething","Controller", FormMethod.Post))
{
}

or using HTML: 或使用HTML:

<form action="@Url.Action("DoSomething","Controller")" method="POST">
... 
</form>

The HTTP verb POST/GET will route your request to the appropriate action. HTTP动词POST / GET将把您的请求路由到适当的操作。 The default is GET. 默认值为GET。

I think that you maybe getting Url.Action() confused with Html.Action() (apologies if I'm wrong). 我认为您可能将Url.Action()Html.Action()混淆了(如果我错了,我们Url.Action()表歉意)。 As someone mentioned in the comments, Url.Action() will just render a URL based on the parameters which is intended for say building anchor tags. 正如评论中提到的那样, Url.Action()将仅基于用于构建锚标签的参数来呈现URL。 Html.Action() on the other hand will invoke an action when building the page for the response at server side which I'm guessing is what your referring too. 另一方面, Html.Action()将在服务器端为响应构建页面时调用一个动作,我猜这也是您所引用的内容。

If that's the case, then you will need to specify the Action's parameters for DoSomething() by specifying the route values like so: 如果是这种情况,那么您将需要通过指定如下所示的路由值来为DoSomething()指定Action的参数:

@Html.Action("DoSomething", "Home", new {MyParam = 2} )

The result of DoSomething(int MyParam) would be injected into the page. DoSomething(int MyParam)的结果将被注入到页面中。 Html.Action is not intended to call a POST so it's not possible to use this on an Action which has been decorated with the POST verb. Html.Action并非旨在调用POST因此无法在已用POST动词修饰的Action上使用它。

问题是我又有一个ajax请求来检查页面是否已完全加载以显示进度条,当从布局中删除该部分代码时,它工作良好,而没有两次调用任何操作方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM