2014-02-05 30 views
0

我是MVC中的新手。@ Html.Action沒有調用控制器內部的動作

在剃刀我需要調用控制器內的方法,但它不適合我。

我的剃刀代碼如下:

@helper SubmitCommnet() 
{ 
    @Html.Action("Post2", "PostShow", new { id = 1111 }); 

} 

和我的控制器是如下:

public class PostShowController : SurfaceController 
{  
    public ActionResult Index() 
    { 
     return null; 
    } 

    public ActionResult Post2(int id) 
    { 
     return null; 
    } 
} 

任何爲什麼它不調用POST2方法的想法?

+1

你正在創建一個幫手權利,這可能是一個愚蠢的問題,但你在視圖中使用助手嗎? –

+1

'@helper SubmitCommnet()'的用途是什麼? –

+1

與其他人說的一樣,如果你只是想重定向,你可以刪除@幫助部分,然後鏈接應該爲你工作 –

回答

2

隨着Razor,你必須使用一個Html.ActionLink要做到這一點,其產生從HTML超鏈接標籤,或直接使用超鏈接標記,樣品:

@Html.ActionLink("Post", // <-- Text for UI 
       "Post2", // <-- ActionMethod 
       "PostShow", // <-- Controller Name. 
       new { id = 1111 }, // <-- Route arguments. 
       null // <-- htmlArguments .. which are none. You need this value 
         //  otherwise you call the WRONG method ... 
         //  (refer to comments, below). 
       ) 
2

您使用Html.ActionLink,就像您Url.Action。記住你也需要指定鏈接文本。東西告訴我,你想下面的方法:

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper, 
    string linkText, 
    string actionName, 
    string controllerName, 
    Object routeValues, 
    Object htmlAttributes 
) 

msdn link

然後你可以使用稱之爲:

@Html.ActionLink("Click Me", "Post2", "PostShow", new { id = 1111 }, null) 

不幸的是,如果你需要提供動作,控制器&路線參數,您需要與htmlAttributes(但是,您可以簡單地通過null)的原型。

+0

您已將Action與ActionLink混淆。 Html.Action不呈現鏈接,它調用Controller動作並返回一個部分。 – AaronLS

+0

@AaronLS:Typod並按照您的評論進行修復。我今天正在睡覺。 (雖然好,但是,ty。) –