Apollo
Apollo

Reputation: 2070

Redirect to a different view when a button is clicked

I am very new at MVC and what I am trying to do it seems simple but I can not figure it out. I have 4 buttons and what I want to do is when the user clicks one of the buttons it takes you to another view. I tried using RedirectAction but nothing happens.

VIEW

@{
ViewBag.Title = "Index";
}
<h2>
Index</h2>
<p>
<button name="button" value="button1">
    One</button>
<button name="button" value="button2">
    Two</button>
<button name="button" value="button3">
    Three</button>
<button name="button" value="button4">
    Four</button>

CONTROLLER

 public class HomeController : Controller
{
    //
    // GET: /Home/   
    public ActionResult Index(string button)
    {

        if (button == "button1")
        {
            return RedirectToAction("Index", "About");
        }
        else if (button == "button2")
        {
            return RedirectToAction("Index", "Contact");
        }

        return View();
    }
}

Upvotes: 0

Views: 933

Answers (1)

Craig W.
Craig W.

Reputation: 18175

In order for the button to actually submit to the server you need type="submit" on the button declaration. You also need a <form> element in your HTML to tell it where to submit.

@using( Html.BeginForm() )
{
    <button name="button" value="button1" type="submit">One</button>
    <button name="button" value="button2" type="submit">Two</button>
    <button name="button" value="button3" type="submit">Three</button>
    <button name="button" value="button4" type="submit">Four</button>
}

Upvotes: 3

Related Questions