简体   繁体   中英

@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?

Is there anyway to pass type GET or POST in @URL.Action or any other way?

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

}

[HttpPost]
public ActionResult DoSomething(MyModel Model)
{

}

In Razor View When I build a link like

<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

Try adding post in the form declaration:

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

or using HTML:

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

The HTTP verb POST/GET will route your request to the appropriate action. The default is GET.

I think that you maybe getting Url.Action() confused with Html.Action() (apologies if I'm wrong). 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. 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.

If that's the case, then you will need to specify the Action's parameters for DoSomething() by specifying the route values like so:

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

The result of DoSomething(int MyParam) would be injected into the page. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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