ASP.NET MVC中如何将Ajax POST请求成功数据传递至另一视图?
Hey there! Let's walk through a few practical ways to get your flightInfo data from the Ajax POST response into another view in your ASP.NET MVC app. I'll cover the most common scenarios you might run into:
Option 1: Redirect to a New Action with Server-Side Data Handoff
This works great if you want to navigate to a full new view after the Ajax call succeeds. We'll use TempData to pass the data between actions (it's designed to persist data across a single redirect request):
Step 1: Update Your Search Action
Modify your action to store the flight data in TempData and return a JSON response with the redirect URL:
[HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Search(SearchParam searchParam) { // Your existing logic to fetch flightInfo var flightInfo = await GetTargetFlightData(searchParam); // Store data in TempData for the next request TempData["FlightInfo"] = flightInfo; // Return JSON with success status and redirect URL return Json(new { success = true, redirectUrl = Url.Action("FlightDetails", "Home") }); }
Step 2: Update the OnSuccess JavaScript Callback
In your frontend, use the redirect URL from the response to navigate to the new action:
function OnSuccess(response) { if (response.success) { window.location.href = response.redirectUrl; } }
Step 3: Create the Target Action and View
Add an action to retrieve the data from TempData and pass it to the view:
public ActionResult FlightDetails() { var flightInfo = TempData["FlightInfo"] as YourFlightInfoModelType; // Handle case where data might be missing if (flightInfo == null) { return RedirectToAction("Index"); } // Optional: Keep TempData if you need to access it again in the same request // TempData.Keep("FlightInfo"); return View(flightInfo); }
Then create a FlightDetails.cshtml view that uses YourFlightInfoModelType as its model.
Option 2: Render a Partial View Directly in the Current Page
If you don't want to navigate away and just want to load the target view's content into the current page, use a partial view:
Step 1: Modify the Search Action to Return a Partial View
Instead of returning JSON, send back a partial view populated with your flight data:
[HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Search(SearchParam searchParam) { var flightInfo = await GetTargetFlightData(searchParam); return PartialView("_FlightDetails", flightInfo); }
Step 2: Update the OnSuccess Callback
Insert the returned partial view HTML into a container on your page:
function OnSuccess(response) { // Replace the content of your target container with the partial view document.getElementById("flight-details-container").innerHTML = response; }
Make sure your main view has a container element like <div id="flight-details-container"></div> where the partial will load.
Option 3: Pass Data via Query String (For Small Datasets)
If your flightInfo is small enough to fit in a URL, you can serialize it and pass it as a query parameter:
Step 1: Update the OnSuccess Callback
Serialize the data to JSON, encode it, and append it to the target URL:
function OnSuccess(flightInfo) { // Serialize and encode the data to avoid URL issues var encodedFlightData = encodeURIComponent(JSON.stringify(flightInfo)); // Navigate to the target action with the data as a query param window.location.href = '@Url.Action("FlightDetails", "Home")?flightData=' + encodedFlightData; }
Step 2: Retrieve Data in the Target Action
Decode and deserialize the query string parameter into your model:
public ActionResult FlightDetails(string flightData) { if (string.IsNullOrEmpty(flightData)) { return RedirectToAction("Index"); } // Decode and deserialize the JSON string var flightInfo = JsonConvert.DeserializeObject<YourFlightInfoModelType>(Uri.UnescapeDataString(flightData)); return View(flightInfo); }
Note: This method has limits due to maximum URL length, so only use it for small datasets.
内容的提问来源于stack exchange,提问作者ramzan ali

