Reputation: 516
I've got a table with controls bound to a model, and I need to call a function when some of these controls' values change. (Recalculating totals and taxes)
The table is in an edit form, and the controls are bound to the model, so I cannot use the onchange event in the controls.
What I've tried:
tried to use the set accessor of the model, however doing this and running in debug the browser crashes and in my debug console I get a access violation error with no context:
private Order order { get { return order; } set { order = value; CalculateTotals(); } }
The program '[11992] iisexpress.exe: Program Trace' has exited with code 0 (0x0). The program '[11992] iisexpress.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'.
Anyone got any ideas?
Upvotes: 1
Views: 6162
Reputation: 45626
You can do something like this:
<EditForm EditContext="@EditContext">
<DataAnnotationsValidator />
<div class="form-group">
<label for="amount">Amount: </label>
<InputNumber Id="amount" Class="form-control" @bind-
Value="@Model.Amount">
</InputNumber>
<ValidationMessage For="@(() => Model.Amount)" />
</div>
<div class="form-group">
<label for="items">Items: </label>
<InputNumber Id="items" Class="form-control" @bind-Value="@Model.Items">
</InputNumber>
<ValidationMessage For="@(() => Model.Items)" />
</div>
</EditForm>
@code
{
private EditContext EditContext;
private Order Model = new Order();
protected override void OnInitialized()
{
EditContext = new EditContext(Model);
EditContext.OnFieldChanged += EditContext_OnFieldChanged;
base.OnInitialized();
}
private void EditContext_OnFieldChanged(object sender,
FieldChangedEventArgs e)
{
Console.WriteLine(e.FieldIdentifier.FieldName);
if (EditContext.Validate())
{
// You can validate the EditContext here, and do necessary
calculation
}
}
}
Hope this helps...
Update:
I've never done it before, but let me suggest the following: Define your child component as follows:
<div class="form-group">
<label for="item">Item: </label>
<select id="Item" class="form-control-sm" @bind="@Model.Item">
@foreach (var item in items)
{
<option value="@item">@item</option>
}
</select>
<ValidationMessage For="@(() => Model.Item)" />
</div>
@code
{
[Parameter]
public Order Model { get; set; }
}
In the parent component, insert the following within the EditForm
Now, you can perform various operations in the child component, as if its code is within the EditForm.
Note: I hope this work... never done it before, and of course I did not execute this code...
Note: You have to provide a list of items here, either pass it from the parent component as a Component Parameter or create a list of items in the the child component, retrieve from database, etc.
Upvotes: 5