【发布时间】:2009-07-01 12:36:24
【问题描述】:
我有一个带有索引操作的产品控制器,它基本上为 ProductController 上的发布和索引(发布操作动词)操作创建视图表单,基本上将产品保存到数据库,但是当发生验证错误时,我返回一个视图( mymodel) else 保存时,我返回 RedirectToAction("Created,"Product") 但由于某些奇怪的原因,当我闯入代码时,它两次而不是一次点击产品控制器操作。因此,产品有 2 条记录一个。
public ActionResult Index()
{
return View()
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(FormCollection fc)
{
// 2 calls are made to this controller
try
{
// save the product
return RedirectToAction("Created");
}
catch(Exception ex)
{
// recreate the model from form collection
return View(viewData); // when a validation error occurs it comes into the catch block
}
}
【问题讨论】:
-
你应该修正你的命名 - 控制器!=动作。我自己还不能编辑你的帖子。 ://
-
如果它们相差 1 个可空参数,则不需要 2 个索引操作。
-
不要传递 FormCollection,而是尝试绑定:“public ActionResult Save(Product product){...}”。
-
您需要发布发布到该控制器操作(保存)的 html 表单。这可能会告诉我们为什么它会被发布两次。
-
您仍然需要向我们展示发布到该索引操作的 HTML 表单。那里可能有一个错误,导致它发布了两次。
标签: asp.net-mvc