Home > Software design >  How do I get object that’s bound to <td>
How do I get object that’s bound to <td>

Time:10-19

In my blazor app,

...
    <td>
        <input type="text" style="border:none;" @bind="todo.Title" />
    </td>
...

how do I get the todo item for the row that has been changed? It doesn't let me use @onchange with @bind and I would like it to continue to be bound, but I also would like to handle an event after that text change that passes in the todo object or somehow get access to todo in the @code.

@page "/todo"

<pagetitle>Todo</pagetitle>

<h1>Todo (@todos.Count(todo => !todo.IsDone))</h1>

<table>
    @foreach (var todo in todos)
    {
        <tr>
            <td>
                <input type="checkbox" @bind="todo.IsDone" />
            </td>
            <td>
                <input type="text" style="border:none;" @bind="todo.Title" />
                @todo.RsDisplay
            </td>
        </tr>
    }
</table>

<input placeholder="Something todo" @bind="newTodo" />
<button @onclick="AddTodo">Add todo</button>

@code {
    private List<TodoItem> todos = new();
    private string? newTodo;

    private void AddTodo()
    {
        if (!string.IsNullOrWhiteSpace(newTodo))
        {
            todos.Add(new TodoItem { Title = newTodo, RsDisplay = "test" });
            newTodo = string.Empty;
        }
    }
}

CodePudding user response:

@oninput does not work with razor, you can use @(IsPostBack ? "oninput" : null) instead. Or you can use change event and keep @bind. @(IsPostBack ? "onchange" : null)

Or you can use ajax for that. Ajax post can also do it and razor works.

@Ajax.ActionLink("click me", "Click", new {}, new AjaxOptions()
{
    HttpMethod = "post"
})

CodePudding user response:

Just add @bind-value with @onchange as below.

<input type="text" style="border:none;" @bind-value="todo.Title" @onchange="YouOnChangeEventMethod" />

this will work for you.

  • Related