簡體   English   中英

在ASP.NET MVC中添加Create方法

[英]Adding Create method in ASP.NET MVC

當我在控制器中添加2 Create Method時,如下所示

        [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。 可以指導我怎么解決。

我的MVC項目中有“產品包含區域”。 其中包含ProductsController.cs,請幫助我如何調用POST操作Create方法。

-馬亨德

請嘗試以下操作:

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

並請使用

[HttpGet]
[HttpPost]

而不是AcceptVerbs,它更干凈。

[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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM