Jeroen
Jeroen

Reputation: 1755

How to make two controller GET methods to post data to the same POST method

So I'm trying to get two controller methods to post data to the same [HttpPost] method and i can't figure it out.

So i've got this method in my controller:

// GET: MpSwitches/Create
public ActionResult Create()
{
   return View();
}

And this method:

public ActionResult FirstTimeStartupCreate()
{
    ViewBag.FirstTime =
    "Je bent doorgestuurd naar deze pagina omdat er nog geen MP-switches in de database staan.";
    return View("Create");
}

They both should post data to this method when the submit button is pressed.

// POST: MpSwitches/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for 
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost, ActionName("FirstTimeStartupCreate")]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "IpAdress")] MpSwitch mpSwitch)
{
    if (ModelState.IsValid)
    {
        var mpSwitchMethods = new MpSwitch();
        if (mpSwitchMethods.CreateMpSwitch(mpSwitch, _db))
        {
            // Success
            return RedirectToAction("Index");
        }
        // Failed to insert into database
        return View("Create", mpSwitch);
    }

    // Form hasn't been filled in correctly.
    return View("Create",mpSwitch);
}

I added the ActionName attribute so the FirstTimeStartupCreate will post to this method. But now the Create method doesn't post to this method anymore.

Any tips on how to tackle this problem?

Upvotes: 1

Views: 117

Answers (1)

Chris
Chris

Reputation: 27599

I don't think that the ActionNameAttribute does what you think it does. It is not there to define how postbacks work, it changes what the name of that action is so that it isn't the method name but whatever you say in the attribute.

So the reason this works for FirstTimeStartupCreate is that the GET version POSTs to the same action name but you now have an action specifically for POST with the name FirstTimeStartupCreate and so it will use that action. You don't have a POST action called Create any more so that doesn't work.

The correct way to do what you want is in the view where you define the form you need to tell it what controller/action it should post to. Html.BeginForm has a lot of overloads but the easiest one takes two additional string parameters for the controller and action.

So in this case you would do Html.BeginForm("Create", "MyController")

Upvotes: 1

Related Questions