基于viewmodel动态更新html

Dynamically updating html based on viewmodel

我目前正在尝试根据我的视图模型中的两个属性更新一些 HTML,这两个属性连接到两个表单组。这是 ASP.NET 核心。

两个表单组:

<div class="form-group">
   <label asp-for="ParticipantAmount">Antal deltagere</label>
   <input asp-for="ParticipantAmount" onchange="Group()" class="form-control" type="number" max="1000" min="1" />
</div>
<div class="form-group">
   <label asp-for="GroupAmount">Antal grupper</label>
   <input asp-for="GroupAmount" class="form-control" onchange="Group()" type="number" max="20" min="1" />
   <p id="GroupSize">0</p>
</div>

视图模型中的属性:

public int ParticipantAmount { get; set; }
public int GroupAmount { get; set; }

脚本部分的javascript方法:

function Group() {
    var groups = Number('@Model.GroupAmount');
    var participants = Number('@Model.ParticipantAmount');
    var size = participants / groups;
    document.getElementById('GroupSize').innerHTML = size;
}

当我尝试将内容记录到控制台时,当表单输入更改时,似乎属性没有在视图模型中更新。

我想我缺少关于我正在尝试做的事情的一个重要方面的一些基本知识,但我似乎无法 google 正确的关键字。希望你能指引我正确的方向。

为了说明 AJAX 调用是如何工作的,我使用 jQuery 制作了一个简约的 Web 应用程序,它应该仅用于学习,代码未准备好用于生产。

剃刀视图。我已将默认值和 ID 添加到您的输入字段,以便在 JavaScript 代码中更容易识别它们。

<div class="form-group">
    <label asp-for="ParticipantAmount">Antal deltagere</label>
    <input asp-for="ParticipantAmount" onchange="Group()" class="form-control" type="number" max="1000" min="1" value="@Model.ParticipantAmount" id="ParticipantAmount" />
</div>
<div class="form-group">
    <label asp-for="GroupAmount">Antal grupper</label>
    <input asp-for="GroupAmount" class="form-control" onchange="Group()" type="number" max="20" min="1" value="@Model.GroupAmount" id="GroupAmount" />
    <p id="GroupSize">0</p>`enter code here`
</div>

JavaScript 代码使用 jQuery 到 get/update 值并发出 AJAX 请求。

<script>
function Group() {
    $.ajax({
        method: "POST",
        url: "/Home/UpdateAmounts",
        data: { ParticipantAmount: $('#ParticipantAmount').val(), GroupAmount: $('#GroupAmount').val() }
    }).done(function (response) {
        $('#GroupSize').html(response);
    });
}
</script>

控制器和视图模型。为 AJAX 调用添加了一个方法。

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View(new ParticipantViewModel());
    }

    // You can call this method via AJAX to update your view model
    [HttpPost]
    public IActionResult UpdateAmounts(int participantAmount, int groupAmount)
    {
        // Validation for negative numbers, and groupAmount cannot be zero
        if (participantAmount < 0 || groupAmount <= 0)
        {
            return Ok(0);
        }

        return Ok(participantAmount / groupAmount);
    }
}

public class ParticipantViewModel
{
    public int ParticipantAmount { get; set; }

    public int GroupAmount { get; set; }
}

为了让事情变得更好更现代,您可以查看 following example 一个使用数据库存储数据并使用 Knockout for UI.

的简单 Web 应用程序