我正在尝试制作一个简单的测试网站,以允许我使用 MVC4 列出、创建、编辑和删除客户对象。
在我的 Controller 中,我有 2 个创建方法,一个是当表单加载控件时使用的 Get 方法,另一个是实际保存数据的 Post。
//
// GET: /Customer/Create
[HttpGet]
public ActionResult Create()
{
return View();
}
//
// POST: /Customer/Create
[HttpPost]
public ActionResult Create(Customer cust)
{
if (ModelState.IsValid)
{
_repository.Add(cust);
return RedirectToAction("GetAllCustomers");
}
return View(cust);
}
但是,当我运行该项目并尝试访问创建操作时,出现错误:
The current request for action 'Create' on controller type 'CustomerController' is ambiguous between the following action methods:
System.Web.Mvc.ActionResult Create() on type [Project].Controllers.CustomerController
System.Web.Mvc.ActionResult Create([Project].Models.Customer) on type [Project].Controllers.CustomerController
我知道它看不出我的 Get 和 Post 方法之间的区别,但我已经添加了属性。这可能是什么原因造成的,我怎样才能让它再次工作?
最佳答案
MVC 不允许您拥有 2 个同名的操作方法。
但是当 http 谓词不同(GET、POST)时,您可以有 2 个具有相同 URI 的操作方法。使用 ActionName 属性设置操作名称。不要使用相同的方法名称。您可以使用任何名称。一个约定是添加http动词作为方法后缀。
[HttpPost]
[ActionName("Create")]
public ActionResult CreatePost(Customer cust)
{
if (ModelState.IsValid)
{
_repository.Add(cust);
return RedirectToAction("GetAllCustomers");
}
return View(cust);
}
关于c# - MVC4 忽略 [HttpGet] 和 [HttpPost] 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12951870/