c# - 如何在 Razor 中动态设置变量?
问题描述
我正在寻找使用文本输入来设置 Razor 语法中的变量的值。这甚至可能吗?
到目前为止,我只能硬编码 Razor 语法中的变量值。
解决方案
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.
推荐阅读
- jquery - Chrome 扩展:$.ajax 不是函数
- css - 使用宽度过渡时如何防止 Chrome 闪烁?
- javascript - Chrome 扩展:webNavigation 同时限制权限范围
- r - 在 R 中绘制分类变量 OLS
- java - Android java xml到json很长
- c# - 如何在 C# 中的表单加载时使用结构填充列表
- sql - Laravel 简单的私人对话结构
- excel - 基于单元格内容的 Microsoft Excel VBA 代码范围
- java - 在javafx中将属性绑定到鼠标
- opennms - OpenNMS SNMP 陷阱停止工作 - 如何进一步排除故障