如何通过JavaScript实现按钮调用控制器动作跳转页面并传递参数?
Hey there! Let's get that Spin button working to redirect to another controller action while passing your Game parameters. Here are two reliable approaches using JavaScript:
1. Direct URL Construction & Redirect
This is great if you only need to pass a few simple parameters (like the Game ID). You can render the model values directly into your JavaScript and build the target URL:
First, update your JavaScript in the .cshtml file:
// Wait for the DOM to load before attaching the click event document.addEventListener('DOMContentLoaded', function() { const spinButton = document.getElementById('spin'); spinButton.addEventListener('click', function() { // Render the Game ID directly from your model (Razor will replace this with the actual value) const gameId = @Model.Id; // Build the URL to your target controller action (adjust the action/controller names as needed) const targetUrl = `/Games/YourTargetAction?gameId=${gameId}`; // Redirect to the new page window.location.href = targetUrl; }); });
Notes for this method:
- If you need to pass more properties from the
Gamemodel, you can add them to the URL query string (e.g.,&gameName=@Model.Name). - Keep in mind that URL query strings have length limits, so this works best for small amounts of data.
2. Hidden Form Submission
For passing multiple properties of the Game object (or avoiding long URLs), use a hidden form. This leverages ASP.NET's model binding to automatically map form fields to your controller's Game parameter:
First, add a hidden form to your .cshtml (place it anywhere in the view):
@using (Html.BeginForm("YourTargetAction", "Games", FormMethod.Get, new { id = "gameRedirectForm" })) { <!-- Add hidden fields for all Game properties you need to pass --> @Html.HiddenFor(m => m.Id) @Html.HiddenFor(m => m.Name) @Html.HiddenFor(m => m.SomeOtherProperty) }
Then add the JavaScript to submit the form when the button is clicked:
document.addEventListener('DOMContentLoaded', function() { const spinButton = document.getElementById('spin'); spinButton.addEventListener('click', function() { document.getElementById('gameRedirectForm').submit(); }); });
Adjusting for POST requests:
If your target controller action uses [HttpPost], change the FormMethod to Post:
@using (Html.BeginForm("YourTargetAction", "Games", FormMethod.Post, new { id = "gameRedirectForm" }))
And update your controller action to accept POST:
[HttpPost] public ActionResult YourTargetAction(Game game) { // Process the game data here return View(); }
Controller Action Setup
Make sure your target controller action is set up to receive the Game parameter correctly. For example:
[AllowAnonymous] public ActionResult YourTargetAction(Game game) { // Do something with the game object return View(game); }
内容的提问来源于stack exchange,提问作者Caleb Farara

