✅ @onchange event not triggering
@page "/"
<PageTitle>Home</PageTitle>
@if(People != null)
{
<h3>People:</h3>
<select @onchange = "ItemSelected" size="4" style="width: 10%;">
@foreach(var person in People)
{
<option value="@person.Id.ToString()">
@person.Name
</option>
}
</select>
@if (SelectedPerson != null)
{
<br />
<div>
Selected Person: @SelectedPerson.Name
</div>
}
else
{
<div>
No name is selected.
</div>
}
}
@code{
Person SelectedPerson;
void ItemSelected(ChangeEventArgs args)
{
SelectedPerson = (from p in People where p.Id == Convert.ToInt32(args.Value.ToString()) select p).FirstOrDefault();
}
private List<Person> People;
public class Person
{
public int Id { get; set; } = 0;
public string Name { get; set; } = "Undefined";
}
protected override void OnInitialized(){
People = new List<Person>();
People.Add(new Person { Id = 1, Name = "Kara Danvers" });
People.Add(new Person { Id = 2, Name = "J'onn J'onzz" });
People.Add(new Person { Id = 3, Name = "Clark Kent" });
People.Add(new Person { Id = 4, Name = "Barry Allen" });
}
}
8 Replies
"Undefined" this is wrong!
use string.Empty. And why are you using linq? To just learn then its fine but if not then use the Find method which will directly return based on the Person Id.
is it enforcing to send you string? @person.Id.ToString() if not just send int so it will be filtered easily
Why is "Undefined" wrong? Just curious as to why. I've tried string.Empty as well, still doesn't work. As far as linq, not sure why the tutorial is using linq.
I am learing as I go, lol
Undefined is also a string. this aint javascript where its a keyword. if your requirement is like setting default names to Undefined then its fine
"undefined" is definitely not wrong, but it definitely wouldn't be my preferred choice either. You could always make the string nullable as well (string?).
In any case, how do you know it's not firing the event?
Oh, this actually looks like its a Server Component, which by default would make it non-interactive. To make it an interactive component and therefore support event binding add
@rendermode InteractiveServer
to the top. That is assuming you're in .NET 8?Yes, I am in .NET 8, let me give it that rendermode tag and check if all is well
Oh my silly goose me.... Lol, once I added the @rendermode InteractiveServer it worked as I wanted... Thank you! I will mark this as completed
How do I mark it as completed, lol, I've only asked two questions in the help threads. Sorry for newby questions!
$close
Use the /close command to mark a forum thread as answered
Thank you! I’ll make a note of the command!