c# - MVC4 忽略 [HttpGet] 和 [HttpPost] 属性

标签 c# asp.net-mvc asp.net-mvc-4 http-post http-get

我正在尝试制作一个简单的测试网站,以允许我使用 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/

相关文章:

c# - ASP.net MVC 4 远程验证不起作用

c# - 由于包装器,使用 $expand 的 OData 中断了强制转换操作

c# - 是否可以访问图形路径中的点?

c# - 使用 MVC Razor View 在表中插入多行

.net - 如何使用户从唯一的一台机器(通过获取 CPU 串行)登录到 ASP.NET-MVC Web 应用程序

c# - 将文本框值从 View 传递到按钮

c# - 如何保存用户最后选择的文件夹?

c# - 避免在锁内和锁外重复if语句

c# - Entity Framework —— View 与表

asp.net-mvc-4 - 如何根据用户访问的位置在 MVC 应用程序中查找用户的国家/地区、州(地区/县/省)和城市?