Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 827
Owen Avatar asked Oct 15 '25 07:10

Owen


1 Answers

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) {}
like image 83
Sergey Gavruk Avatar answered Oct 18 '25 00:10

Sergey Gavruk