'ASP.NET Core - Updating ViewModel based on View changes without refreshing page
As the title states, I am building a website and I have a form for making reservations. Whenever a user changes a datetime or ticks a checkbox, I would be able to refresh the price calculation without refreshing the page. I've tried to explore many solutions, but I couldn't get anything to do I want it to.
Ideas I had:
The ViewModel could always be updated whenever View changes (how?), then, the setter of some property could be set to be dependant on one of the fields, so it should also update the values of that property in the View?
Turn it into a RazorComponent, then I would maybe be able to refresh the component with new data somehow?
Not sure whether either would work. The entire form is already built and integrated into everything else on the website, just not sure how to add the price calculation.
Code of the View: `@model Reservation
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="row">
<div class="col-1"></div>
<div class="col-12 col-md-7">
<div class="row">
<div class="col-5">
@Html.LabelFor(model => model.StartDate) <span class="mandatory-field-star">*</span>
@Html.EditorFor(model => model.StartDate, new { htmlAttributes = new { @class = "w-100"} }) <br/>
@Html.ValidationMessageFor(model => model.StartDate)
</div>
</div>
<div class="row">
<div class="col-5">
@Html.LabelFor(model => model.FinalDate) <span class="mandatory-field-star">*</span>
@Html.EditorFor(model => model.FinalDate, new { htmlAttributes = new { @class = "w-100"} }) <br/>
@Html.ValidationMessageFor(model => model.FinalDate)
</div>
</div>
</div>
<div class="col-12 col-md-3">
<div class="card">
<div class="card-body">
<h5 class="green-text-color">Summary</h5>
<div class="card-text">
<div class="row">
<div class="col-7">item</div>
<div class="col-5 align-right">2.50</div>
</div>
<hr class="card-hr"/>
<div class="row">
<div class="col-7">Total</div>
<div class="col-5 darkGreen-text-color align-right font-weight-bold">2.50</div>
<button type="submit" class="mt-3">Order</button>
</div>
</div>
</div>
</div>
</div>
<div class="col-1"></div>
</div>
@Html.ReCaptcha()
}`
TL;DR desired behavior: price gets calculated inside the ViewModel essentially, so when View changes, ViewModel's property should update so the change gets reflected on the price property within ViewModel.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
