【问题标题】:Can i have more than one Post method in asp.net mvc controller?我可以在 asp.net mvc 控制器中有多个 Post 方法吗?
【发布时间】:2019-03-07 21:28:18
【问题描述】:

我有两个视图,一个是 CustomerDetail.cshtml,另一个是 PAymentDetail.cshtml,我有一个控制器 QuoteController.cs。

两个视图都有提交按钮和两个视图的 HTTPPOST 方法都在 QuoteController.cs 中。

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

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

现在,当我点击付款详情的提交按钮时,它正在调用/路由到 CustomerDetail 的 HttpPost 方法,而不是 PAymentDetail。

有人可以帮我吗?我做错了什么?两者的表单方法都是POST。

【问题讨论】:

  • 您可能需要检查您的路由配置,尤其是在您修改了默认配置的情况下。

标签: asp.net-mvc asp.net-mvc-3


【解决方案1】:

对于 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
}

祝你好运。

【讨论】:

    【解决方案2】:

    绝对!只要确保您发布到正确的操作方法,检查您呈现的 HTML 的 form 标签。

    另外,FormCollection 不是 MVC 的好设计。

    【讨论】:

    • 您可以添加一些关于一些好的设计的信息 :) 就像采用 class 或类似的代替。
    • 我有一些 标签,它们不是使用 razor 视图创建的,这些值需要在控制器方法中捕获。你知道有什么更好的方法吗(除了 FormCollection)。另外,我们可以在同一个控制器中有两个 post 方法吗?
    【解决方案3】:

    如果你只想有一个 url,这里是另一种方法:http://www.dotnetcurry.com/ShowArticle.aspx?ID=724

    这个想法是使用一个表单元素(按钮或隐藏元素)来决定,哪个表单已经提交。然后您编写一个自定义操作选择器 (http://msdn.microsoft.com/en-us/library/system.web.mvc.actionmethodselectorattribute.aspx),它决定将调用哪个操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-12
      • 2011-11-04
      • 1970-01-01
      • 2016-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多