You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

BLAZOR + MVC:如何从Blazor页面向MVC控制器传递数据

Absolutely feasible! You don’t have to rely on database roundtrips to pass data from a Blazor page to an MVC controller—there are several straightforward, efficient alternatives tailored to different scenarios. Let’s break down the most practical ones:

1. Direct HTTP Requests (Ideal for Complex Objects)

This is the most common and flexible approach. You can use Blazor's built-in HttpClient to send POST/GET requests directly to your MVC controller action, passing data in the request body or as parameters.

Blazor Page Code:

First, inject HttpClient into your Blazor component:

@inject HttpClient Http
@inject NavigationManager NavManager

<button @onclick="SendDataToMvc">Send Data to MVC Controller</button>

@code {
    private async Task SendDataToMvc()
    {
        var data = new UserData 
        {
            Username = "Filip",
            Age = 30,
            Preferences = new List<string> { "Blazor", "MVC" }
        };

        // Send POST request to MVC controller action
        var response = await Http.PostAsJsonAsync("/User/ProcessBlazorData", data);
        
        if (response.IsSuccessStatusCode)
        {
            // Navigate to the MVC result page after successful submission
            NavManager.NavigateTo("/User/Result");
        }
    }

    // Define your data model to match what the MVC controller expects
    public class UserData
    {
        public string Username { get; set; }
        public int Age { get; set; }
        public List<string> Preferences { get; set; }
    }
}

MVC Controller Action:

Then, create an action to receive and process the data:

public class UserController : Controller
{
    [HttpPost]
    public IActionResult ProcessBlazorData(UserData data)
    {
        // Process the data (e.g., validate, save to DB if needed, or use directly)
        TempData["ProcessedData"] = JsonSerializer.Serialize(data);
        
        return RedirectToAction("Result");
    }

    public IActionResult Result()
    {
        var data = JsonSerializer.Deserialize<UserData>(TempData["ProcessedData"] as string);
        return View(data);
    }

    // Match the model from Blazor
    public class UserData
    {
        public string Username { get; set; }
        public int Age { get; set; }
        public List<string> Preferences { get; set; }
    }
}

2. Query String Parameters (Great for Simple, Small Data)

If you're navigating directly from Blazor to an MVC page and only need to pass simple values (strings, numbers), append them to the URL as query parameters. MVC can bind these directly to action parameters.

Blazor Navigation Code:

@inject NavigationManager NavManager

<button @onclick="NavigateToMvcWithData">Go to MVC Page with Data</button>

@code {
    private void NavigateToMvcWithData()
    {
        string userId = "123";
        string userRole = "Admin";
        // Escape special characters to avoid URL issues
        var url = $"/User/Details?id={Uri.EscapeDataString(userId)}&role={Uri.EscapeDataString(userRole)}";
        NavManager.NavigateTo(url);
    }
}

MVC Controller Action:

public class UserController : Controller
{
    public IActionResult Details(string id, string role)
    {
        // Use the parameters directly in your view or logic
        ViewBag.UserId = id;
        ViewBag.UserRole = role;
        return View();
    }
}

3. Session State (For Persisting Data Across Requests)

If you're using Blazor Server (WebAssembly runs client-side and lacks direct server session access), you can use ISession to store data temporarily, then retrieve it in your MVC controller. This works well for keeping data alive across multiple requests in the same user session.

Blazor Page Code:

First, make sure IHttpContextAccessor is registered in your Program.cs, then inject it:

@inject IHttpContextAccessor HttpContextAccessor
@inject NavigationManager NavManager

<button @onclick="StoreDataInSession">Store Data in Session</button>

@code {
    private void StoreDataInSession()
    {
        var data = new UserData { Username = "Filip", Age = 30 };
        string jsonData = JsonSerializer.Serialize(data);
        // Store serialized data in session
        HttpContextAccessor.HttpContext.Session.SetString("BlazorUserData", jsonData);
        
        NavManager.NavigateTo("/User/ReadSessionData");
    }

    public class UserData
    {
        public string Username { get; set; }
        public int Age { get; set; }
    }
}

MVC Controller Action:

public class UserController : Controller
{
    public IActionResult ReadSessionData()
    {
        var jsonData = HttpContext.Session.GetString("BlazorUserData");
        if (!string.IsNullOrEmpty(jsonData))
        {
            var userData = JsonSerializer.Deserialize<UserData>(jsonData);
            // Use the data in your view or logic
            return View(userData);
        }
        return View();
    }

    public class UserData
    {
        public string Username { get; set; }
        public int Age { get; set; }
    }
}

Don’t forget to add session services in Program.cs:

builder.Services.AddSession();
// ...
app.UseSession();

4. TempData (MVC's Built-in Temporary Storage)

TempData is designed for one-time data transfer between actions/controllers in MVC. Blazor Server can access it via IHttpContextAccessor too—perfect if you need data available only for the next request.

Blazor Page Code:

@inject IHttpContextAccessor HttpContextAccessor
@inject ITempDataDictionaryFactory TempDataFactory
@inject NavigationManager NavManager

<button @onclick="SetTempDataForMvc">Set TempData</button>

@code {
    private void SetTempDataForMvc()
    {
        using var tempData = TempDataFactory.CreateTempData(HttpContextAccessor.HttpContext);
        tempData["Greeting"] = "Hello from Blazor!";
        tempData["UserInfo"] = JsonSerializer.Serialize(new { Name = "Filip", Id = 42 });
        
        NavManager.NavigateTo("/User/ReadTempData");
    }
}

MVC Controller Action:

public class UserController : Controller
{
    public IActionResult ReadTempData()
    {
        string greeting = TempData["Greeting"] as string;
        var userInfo = JsonSerializer.Deserialize<dynamic>(TempData["UserInfo"] as string);
        
        ViewBag.Greeting = greeting;
        ViewBag.UserName = userInfo.Name;
        return View();
    }
}

Which One Should You Choose?

  • Use HTTP Requests for complex objects or background data processing.
  • Use Query Strings for simple, non-sensitive data that’s safe to expose in URLs.
  • Use Session if you need to persist data across multiple requests in the same session.
  • Use TempData for one-time data transfer between Blazor and MVC actions.

内容的提问来源于stack exchange,提问作者Filip

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 10:27:40