2

我想在一个创建页面上有两个单独的表单,并且每个表单在控制器中都有一个操作。

在视图中:

<% using (Html.BeginForm()) { %>
    // Contents of the first (EditorFor(Model.Product) form.
    <input type="submit" />
<% } %>
<% using (Html.BeginForm()) { %>
    // Contents of the second (generic input) form.
    <input type="submit" />
<% } %>

在控制器中:

// Empty for GET request
public ActionResult Create() {
    return View(new ProductViewModel("", new Product()));
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Product product) {

    return View(new ProductViewModel("", product));
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(string genericInput) {
    if (/* problems with the generic input */) {
        ModelState.AddModelError("genericInput", "you donkey");
    }

    if (ModelState.IsValid) {
        // Create a product from the generic input and add to database
        return RedirectToAction("Details", "Products", new { id = product.ID });
    }

    return View(new ProductViewModel(genericInput, new Product()));
}

结果"The current request for action 'MyMethod' on controller type 'MyController' is ambiguous between the following action methods"- 错误或调用了错误的创建操作。

解决方案?

  • 将这两个 POST Create 操作合并为一个公共ActionResult Create(Product product, string genericInput);
  • 以不同的方式命名 POST Create 操作之一并将新名称添加到相应的Html.BeginForm()

我不知道这些有什么警告。你会如何解决这个问题?

4

2 回答 2

3

您不能有两个具有相同名称和动词但仅在参数类型上有所不同的动作。恕我直言,假设它们执行不同的任务并接受不同的输入,以不同的方式命名您的两个操作将是一个好主意。

于 2010-07-25T19:21:32.383 回答
1

实际上,如果您对 BeginForm() 调用更具体,我相信您可以做到这一点。

Using(Html.BeginForm<ControllerName>(c => c.Create((Product)null)) { } 
Using(Html.BeginForm<ControllerName>(c => c.Create((string)null)) { }
于 2010-08-30T18:00:01.030 回答