How to pass data from Blazor component inside a view to a controller action method?
This section outlines how to pass data from blazor component inside a view to a controller Action method. To pass parameters from a Razor component to an MVC controller, you can use a Singleton service. By injecting the service into the pages, you can retrieve the data and use it as per your requirement.
Please find the following code snippet and sample for reference:
Program.cs
using Sample.Models;
using Syncfusion.Blazor;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddServerSideBlazor();
builder.Services.AddSyncfusionBlazor();
builder.Services.AddSingleton<MyDataModel>();
var app = builder.Build();
//…
SelectDates.razor
@using Sample.Controllers;
@using Syncfusion.Blazor
@using Syncfusion.Blazor.Calendars
@using System.Globalization
@using Microsoft.Extensions.Logging
@using Sample.Models
@inject MyDataModel myDataModel
<form method="post" action="/Home/ProcessData">
<div class="col-md-2 control-section">
<div class="control-wrapper">
<label class="example-label">Seleziona le date:</label>
<SfDateRangePicker TValue="DateTime?" Placeholder="Scegli un periodo"
@bind-StartDate="@myDataModel.StartValue" @bind-EndDate="@myDataModel.EndValue"
@onkeypress='@KeyPressed' ShowClearButton="true">
<DateRangePickerPresets>
<DateRangePickerPreset Label="Questa settimana" Start="@WeekStart" End="@WeekEnd"></DateRangePickerPreset>
<DateRangePickerPreset Label="Questo mese" Start="@MonthStart" End="@MonthEnd"></DateRangePickerPreset>
<DateRangePickerPreset Label="Lo scorso mese" Start="@LastMonthStart" End="@LastMonthEnd"></DateRangePickerPreset>
</DateRangePickerPresets>
</SfDateRangePicker>
</div>
<br />
<button type="submit">Estrai</button>
</div>
</form>
//…
HomeController.cs
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Mvc;
using Sample.Models;
using System.Diagnostics;
namespace Sample.Controllers
{
public class HomeController : Controller
{
private readonly MyDataModel myDataModel;
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger, MyDataModel MyDataModel)
{
_logger = logger;
myDataModel = MyDataModel;
}
public IActionResult Index()
{
return View();
}
public IActionResult Privacy(MyDataModel model)
{
return View(model);
}
public IActionResult ProcessData()
{
var model = new MyDataModel
{
StartValue = myDataModel.StartValue,
EndValue = myDataModel.EndValue
};
return RedirectToAction("Privacy", model);
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}