Question

I want to have two separate forms on a single create page and one action in the controller for each form.

In the view:

<% 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" />
<% } %>

In the controller:

// 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()));
}

Results in "The current request for action 'MyMethod' on controller type 'MyController' is ambiguous between the following action methods" - error or the wrong Create action is called.

Solutions?

  • Combine those two POST Create actions into one public ActionResult Create(Product product, string genericInput);
  • Name one of the POST Create actions differently and add the new name to the corresponding Html.BeginForm()

I have no idea what are the caveats in these. How would you solve this?

Was it helpful?

Solution

Actually, I believe you can do this if you are more specific with your BeginForm() call.

Using(Html.BeginForm<ControllerName>(c => c.Create((Product)null)) { } 
Using(Html.BeginForm<ControllerName>(c => c.Create((string)null)) { }

OTHER TIPS

You cannot have two actions with the same name and verb that differ only with argument types. IMHO naming your two actions differently would be a good idea assuming that they perform different tasks and take different inputs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top