views:

38

answers:

2

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?

+1  A: 

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.

Darin Dimitrov
+1  A: 

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)) { }
ARM
Hey! Thanks for the info. Unfortunately I wasn't able to find a generic version `Html.BeginForm<T>` of the `Html.BeginForm` extension method. Could you kindly reference where I can find this extension? I tried both, MVC 2 and 3.
randomguy
MVC Futures. You can find it at http://aspnet.codeplex.com/releases/view/41742
ARM