asp.net-mvc-2model-bindingcontroller-actionhtml-post

How to support multiple forms that target the same Create action on the same page?


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?

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


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)) { }