【问题标题】:Adding Create method in ASP.NET MVC在 ASP.NET MVC 中添加 Create 方法
【发布时间】:2012-07-04 02:50:30
【问题描述】:

当我在控制器中添加 2 个创建方法时,如下所示

        [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult Create()
    {
        Product.Models.Product p = new Models.Product();
       //update DB
        try
        {
            return RedirectToAction("GetAll");
        }
        catch (Exception)
        {

            return View(p);
        }

    } 

    //
    // POST: /Product/Default1/Create

     [AcceptVerbs(HttpVerbs.Posr)]
    public ActionResult Create(FormCollection collection)
    {
        try
        {
            if (myProduct.Products == null)
            {
                myProduct.Products = new List<Models.Product>();
            }
            Product.Models.Product p = new Product.Models.Product();
            p.Name =  collection["Name"];
            p.ProductType = collection["ProductType"];
            p.Id = myProduct.Products.Count + 1;

            myProduct.Products.Add(p);


            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }

如果我评论 GET 动作动词并运行应用程序,应用程序会抛出错误资源未找到。它不会触发创建操作。我的 html 有 @using (Html.BeginForm())

我更改了表单,即使这样我也得到了同样的错误。如果我取消注释 GET 动作动词,那么总是 GET 方法启动。我想调用 POST Create action 。可以any1指导我如何解决。

我的 MVC 项目中有产品有区域。里面有 ProductsController.cs 请帮我如何调用 POST action Create 方法。

-马亨德

【问题讨论】:

  • 您在帖子的 AcceptVerbs 属性上有一个类型。 “.Posr” -> “.Post”
  • 我能够理解在 ASP.NET MVC 中使用不同动词的 2 种方法的含义。但问题是如何强制在 MVC 中始终使用 POST。有没有HTTP Constraint,需要在路由策略中设置
  • 如果你注释掉 GET Create 方法,你将如何发布然后表单返回到 POST Create 方法?

标签: c# asp.net-mvc


【解决方案1】:

尝试以下操作:

@using (Html.BeginForm("Create", "Default1", new { area = "Product" }, FormMethod.Post)) {
// Your Form
}

请使用

[HttpGet]
[HttpPost]

而不是 AcceptVerbs,它更简洁。

【讨论】:

    【解决方案2】:
    [HttpGet] // Or even if you dont put this, it will be treated as GET
    public ActionResult Create()
    {
         // your code goes here
    }
    
    [HttpPost]
    public  ActionResult Create(Model yourModel)
    {
        // your code goes here 
    }
    
    in your view 
    @using(Html.BeginForm("HandleForm", "Home")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-01
      • 1970-01-01
      • 2011-11-05
      相关资源
      最近更新 更多