Reputation: 410
Given this Edit.cshtml
:
@model User
<form asp-action="Edit">
<component type="typeof(EditUser)" render-mode="ServerPrerendered" param-User="Model" />
<input type="submit" value="Save" />
</form>
and this EditUser.razor
:
<input class="form-control" type="text" @bind-value="User.Name" />
@code {
[Parameter]
public User User { get; set; }
}
with this User.cs
model:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
and this UserController.cs
:
// GET
public async Task<IActionResult> Edit(int id)
{
var user = await _context.Users.FindAsync(id);
if (user == null)
{
return NotFound();
}
return View(user);
}
[HttpPost]
public async Task<IActionResult> Edit(int id, [Bind("Id,Name")] User user)
{
if (ModelState.IsValid)
{
_context.Update(user);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(user);
}
But this doesn't seem to work, since the User passed into the Edit method is empty. How do I pass the User with the inputted values in the Blazor component to the UserController? Is there any way to get the input values from a Blazor component into the controller at all?
Upvotes: 2
Views: 3478
Reputation: 31
You should help yourself with a little JavaScript. Basically, it will use JSRuntime (proper way to communicate between Blazor and JS) to send changed data back to the view. It is maybe not exacly how it works under the hood, but you should get the idea :-)
a) Add a hidden item somewhere in the form section:
<input type="hidden" asp-for="Name" id="Name" />
b) Add some JS at the bottom of Edit.cshtml. This function will get the data from Blazor component and pass them to the input item.
<script>
window.updateUserName = function (userName) {
document.getElementById('Name').value = userName;
}
</script>
a) Some changes in your input item - should looks like this:
<input class="form-control" @onchange="async (e) => { User.Name = e.Value.ToString(); await UpdateUserName(); }" value="@User.Name" />
This enables invoking custom code to send changed data back to the view, using the method mentioned below.
b) In @code section:
public async Task UpdateUserName()
{
await JSRuntime.InvokeVoidAsync("updateUserName", User.Name);
}
And thats all. I hope it helps.
Upvotes: 2