首页 > 解决方案 > 如何在 Razor 中动态设置变量?

问题描述

我正在寻找使用文本输入来设置 Razor 语法中的变量的值。这甚至可能吗?

到目前为止,我只能硬编码 Razor 语法中的变量值。

标签: c#razormodel-view-controller

解决方案


Pages and Views (aka. cshtml pages with razor syntax) only renders for once and respond them as static html contents.

As long as the page is loaded at the front end, the razor page has finished its work, and the request scope is disposed. Thus no status would remain at the back end.

This is called one-way data binding and is how MVC works, the data gets updated by a new request to a controller and the the controller update the data and return a new Page or View rendered.

If you wish to keep the razor page alive while the page is displayed and handle user interaction with C# instead of Javascript, you have to use Blazor which is a part of ASP.NET Core 3.0.

To get started you need to install .NET Core 3.0 SDK with Visual Studio 2019 16.3 or the latest Visual Studio Code

With blazor, you can make two-way data binding like this:

<h1>@_value</h1>

<input @bind="_value" @bind:event="oninput" />

@code
{
    private string _value;
}

The content in the h1 element, the _value field, and the value of the input element would be binded in real time to reflect any changes of each other.


推荐阅读