2013-08-02 40 views
3

我有兩個看法,一個是CustomerDetail.cshtml,另一個是PAymentDetail.cshtml,我有一個控制器QuoteController.cs。我可以在asp.net mvc控制器中使用多個Post方法嗎?

對於這兩個視圖都有提交按鈕和HTTPPOST方法都在QuoteController.cs中。

[HttpPost] 
public ActionResult CustomerDetail(FormCollection form) 
{ 
} 

[HttpPost] 
public ActionResult PAymentDetail(FormCollection form) 
{ 
} 

現在,當我點擊提交的支付信息按鈕,它呼籲/路由HttpPost爲CustomerDetail而非PAymentDetail的方法。

任何人都可以幫助我嗎?我做錯了什麼?表單方法都是POST。

+0

您可能想要檢查您的路由配置,特別是如果您已將其從默認設置修改。 – MushinNoShin

回答

4

對於PaymentDetail,您可以在視圖使用:

@using(Html.BeginForm("PAymentDetail","Quote",FormMethod.Post)) 
{ 
    //Form element here 
} 

結果HTML將

<form action="/Quote/PAymentDetail" method="post"></form> 

同爲顧客詳細

@using(Html.BeginForm("CustomerDetail","Quote",FormMethod.Post)) 
{ 
    //Form element here 
} 

希望有所幫助。只要這些方法具有不同的名稱,在同一個控制器中使用兩種post方法並不是問題。

對於除FormCollection以外的更好的方法,我推薦這個。 首先,創建一個模型。

public class LoginModel 
{ 
    public string UserName { get; set; } 
    public string Password { get; set; } 
    public bool RememberMe { get; set; } 
    public string ReturnUrl { get; set; } 

} 

然後,在視圖中:

@model LoginModel 
@using (Html.BeginForm()) { 

<fieldset> 
    <div class="editor-label"> 
     @Html.LabelFor(model => model.UserName) 

    </div> 
    <div class="editor-field"> 
     @Html.EditorFor(model => model.UserName) 
     //Insted of razor tag, you can create your own input, it must have the same name as the model property like below. 
     <input type="text" name="Username" id="Username"/> 
    </div> 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.Password) 
    </div> 
    <div class="editor-field"> 
     @Html.EditorFor(model => model.Password) 
    </div> 
    <div class="editor-label"> 
     @Html.CheckBoxFor(m => m.RememberMe)  
    </div> 
</fieldset> 

}

這些用戶輸入將被映射到控制器中。

[HttpPost] 
public ActionResult Login(LoginModel model) 
{ 
    String username = model.Username; 
    //Other thing 
} 

祝你好運。

1

絕對!只要確保您發佈的是正確的操作方法,請檢查您呈現的HTML的form標籤。另外,FormCollection不是一個好的MVC設計。

+0

你可以在一些好的設計上添加一些信息:)喜歡參加'class'或類似的。 – NoLifeKing

+0

我有一些標籤,不是使用剃鬚刀視圖創建的,這些值需要在控制器方法中捕獲。你是否知道這樣做的更好方式(FormCollection除外)。而且,我們可以在同一個控制器中使用兩種後置方法嗎? – PaRsH

相關問題