Search code examples
c#asp.net-mvcrazor

Can I pass a value from a button in a view to the controller using C# ASP.NET MVC and Razor


I'm pretty new to ASP.NET MVC. I have an index page that pulls 3 random values from a database and displays them. I also have a button on that page that I want to randomize the returned values and display them. I have attempted putting a button into the view

<a href='@Url.Action("randButton","Home")' class="btn btn-primary">Randomize</a>

This approach is so close to giving me the desired result, but the problem is that, in production, when it redirects to the randButton page, I am able to refresh the page and all the randomization code fires again. I would like for it to randomize when the button is clicked, but not when the page is refreshed from the browser.

Index Controller:

    public IActionResult Index()
    {
        if (checkDate())
        {
            setSelections();
        }

        FetchData();
        return View(restaurants);
    }

    public IActionResult randButton()
    {
        resetSelections();
        setSelections();
        FetchData();
        return View("Index", restaurants);
    }

I also tried copying the return value from index to randbutton.

I'll be happy to provide any further information required.


Solution

  • If I understand correctly, it sounds like the problem is that reloading the page re-invokes the randButton() action. This is probably because of how that action is responding:

    return View("Index", restaurants);
    

    It's returning a view, which means the URL in the browser is to the randButton() action, which means reloading the page will re-invoke that action.

    Separate commands from queries. Index is a query (it doesn't modify data or state, it just displays it) and randButton is a command (it modifies data or state).

    After performing the command, issue a re-direct to perform the query:

    return RedirectToAction("Index");
    

    So when the user clicks the button, they invoke the command and then the result of the command is a redirect response navigating them back to the Index to query the current state. Then if they reload the page, they're just reloading the query.