【问题标题】:.NET MVC 4 HttpPost going wrong.NET MVC 4 HttpPost 出错
【发布时间】:2012-09-27 08:24:11
【问题描述】:

.NET MVC 4 有一个有趣的小问题。 我正在尝试了解它是如何工作的,在做了一些教程之后,我一直遇到同样的问题。

下面是我的默认索引方法,页面加载时应该调用它。

   public ActionResult Index() {
       var result = (from Product in db.Products
                     orderby Product.Id ascending
                     select Product);
       return View(result.ToList());
   }

该方法从我的数据库中返回一个产品列表..

@using (Html.BeginForm("Index", "Stap1", FormMethod.Post, new { id = "form1" }))
{
    <select id="select" size="4" name="product">
        @foreach (var item in Model)
        {
            <option value="@item.Id" >@Html.DisplayFor(modelItem => item.Naam), @Html.DisplayFor(modelItem => item.Prijs)</option>            
        }
    </select>
    <input type="submit" value="Voeg Toe!" name="Add" />
}

我添加了一个函数来捕获表单的发布数据。像这样..

[HttpPost]
public ActionResult Index(int product = 0) {
                var result = (from Product in db.Products
                              orderby Product.Id ascending
                              select Product);
                System.Diagnostics.Debug.WriteLine("wrong function called!");
                return View(result.ToList());
            }

但是,当我尝试加载索引页面时,您可以看到这是非常基本的东西。它调用'overloaded httppost Index()'而不是正常的。为什么它在没有发布时调用HTTPPOST方法?

【问题讨论】:

  • Post Action 加载而不发布表单?
  • 或者页面加载时调用了错误的方法。知道是什么原因造成的吗?
  • 除非您特别需要表单的id,否则您只需使用代码@using(Html.BeginForm)){ },因为这会自动回发到您所在的同一控制器/操作。例如/Stap1/Index 默认会回发到 /Stap1/Index。
  • 我希望它在页面加载时加载 Index(),然后当我按下添加按钮时,它会调用 Index(int product) 方法。这是一个基本的获取页面、发布数据、重新加载页面查看系统,但我无法使用 Index 方法。
  • @user1069574:同意蒂姆·B·詹姆斯的观点。您的操作结果很好,您可以按照自己的方式超载您的操作。不过,正如蒂姆所说,您的表格正在发布到另一个行动中。您是否更改了 RouteConfig 中的任何内容?

标签: .net asp.net-mvc http-post


【解决方案1】:

我检查了您的代码,这是正确的行为。 您的应用程序从呈现 Index 视图的 HomeController 开始。

在你看来,我发现了这段代码:

@using (Html.BeginForm("Index", "Stap1", FormMethod.Post, new { id = "form1" }))
{
   <input type="submit" value="Start!" name="start" />
}

所以您实际上是在发布到 Stap1Controller 操作 Index
如果您想在不发布的情况下调用(HttpGet)您的索引,您应该执行以下操作:

@Html.ActionLink("Start!", "Index", "Stap1")

【讨论】:

  • 你先生,真棒。谢谢一堆,我从没想过它会从上一页被调用,似乎我通过在 indexController 中制作该表单做了一些糟糕的页面连接。谢谢一堆!
  • 没问题。很高兴我帮助了 ;-)
猜你喜欢
  • 2012-03-30
  • 1970-01-01
  • 1970-01-01
  • 2012-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多