Owen
Owen

Reputation: 4397

MVC - GET & POST actions with the same name and parameters in the same controller

I'm working on an MVC4 project, and I have two actions in the same controller with the same name and parameters:

public ActionResult Create(CreateBananaViewModel model)
{
    if (model == null)
        model = new CreateBananaViewModel();

    return View(model);
}

[HttpPost]
public ActionResult Create(CreateBananaViewModel model)
{
    // Model Save Code...

    return RedirectToAction("Index");
}

The reason I want to pass an existing model into my Create method is to clone and then modify an existing model.

Obviously the compiler doesnt like this, so I've changed one method to look like this:

[HttpPost]
public ActionResult Create(CreateBananaViewModel model, int? uselessInt)
{
    // Model Save Code...

    return RedirectToAction("Index");
}

Is this perfectly acceptable? Or is there a nicer way of getting around this problem?

EDIT / SOLUTION:

Looks like I completely over complicated the situation. Here's my solution

public ActionResult Duplicate(Guid id)
{
    var banana = GetBananaViewModel(id);

    return View("Create", model);
}

public ActionResult Create()
{
    var model = new CreateBananaViewModel();

    return View(model);
}

Upvotes: 4

Views: 8140

Answers (1)

Sergey Gavruk
Sergey Gavruk

Reputation: 3558

Do you really need a model param at GET Create action? You can do something like this:

public ActionResult Create()
{
    var model = new CreateBananaViewModel();

    return View(model);
}

or, if you wish to receive some query data to the action (www.mysite.com/banana/create?bananaType=yellow)

public ActionResult Create(string bananaType, string anotherQueryParam)
{
    var model = new CreateBananaViewModel()
    {
       Type = bananaType
    };
    return View(model);
}

and leave your POST action as it is

[HttpPost]
public ActionResult Create(CreateBananaViewModel model) {}

Upvotes: 6

Related Questions