如何支持针对同一页面上的同一创建操作的多个表单?
-
29-09-2020 - |
题
我想在单个创建页面上有两个单独的表单,并在控制器中为每个表单设置一个操作。
在视图中:
<% 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);
- 以不同的方式命名一个帖子创建操作,并将新名称添加到相应的
Html.BeginForm()
我不知道这些有什么警告。你会如何解决这个问题?
解决方案
实际上,我相信如果你对BeginForm()调用更具体,你可以做到这一点。
Using(Html.BeginForm<ControllerName>(c => c.Create((Product)null)) { }
Using(Html.BeginForm<ControllerName>(c => c.Create((string)null)) { }
其他提示
不能有两个具有相同名称和动词的操作,这些操作仅因参数类型而不同。恕我直言,以不同的方式命名你的两个动作将是一个好主意,假设他们执行不同的任务并采取不同的输入。
不隶属于 StackOverflow