【发布时间】:2015-08-28 13:28:44
【问题描述】:
我正在尝试通过 html beginForm 发布表单,但调用的方法始终是 [httpPost] 索引,而不是帖子中指定的方法(搜索)。
我做错了什么?
这是我的表格:
@using (Html.BeginForm("Search", "MyController", FormMethod.Post))
{
<p>
Postal Code: @Html.TextBoxFor(m => m.PostalCode) <br />
City: @Html.TextBoxFor(m => m.PostalCodeCity ) <br />
Address: @Html.TextBoxFor(m => m.Address) <br />
<input type="submit" value="submit" />
</p>
}
我的模特:
public class MyModel
{
public string PostalCode { get; set; }
public string PostalCodeCity { get; set; }
public string Address { get; set; }
}
我的路线:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Ignore("{resource}.axd/{*pathInfo}");
//Routing for ASP.NET MVC Controllers
routes.MapRoute(
name: "ControllersRoute",
url: "mvc/{controller}/{action}/{id}",
defaults: new { id = UrlParameter.Optional });
//Routing for Web Api Controller
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional });
我的控制器方法
public class MyController : Controller
{
/// <summary>
/// Gets or sets the message.
/// </summary>
[Category("String Properties")]
public string Message { get; set; }
/// <summary>
/// This is the default Action.
/// </summary>
public ActionResult Index()
{
MyModel model = new MyModel();
return View("Default", model);
}
[HttpPost]
public ActionResult Index(MyModel model)
{
//Refresh model attending session variables
return View("Default", model);
}
[HttpPost]
public ActionResult Search(MyModel model)
{
//model work
return View("Default", model);
}
}
更新
@markpsmith 建议我检查表单操作,但这是错误的。 它是 action="order-calendar" 而不是我将其更改为 action="order-calendar/search" 并调用了操作 Search。
这是路线问题吗?
【问题讨论】:
-
您是否调试过代码以确认它没有命中
Search? -
是的,我已经做到了:/ 我并没有意识到可能出了什么问题
-
能否检查生成的 HTML 以确认表单操作为
Search? -
可能与它是一个 WebApi 应用程序有关。需要默认路由吗?
-
你的控制器被命名为
MyController,因此它必须是@using (Html.BeginForm("Search", "My", FormMethod.Post))(第二个参数是"My",而不是"MyController") - 但其他cmets建议你有更多的问题不仅仅是这个
标签: asp.net-mvc sitefinity html.beginform