简体   繁体   English

如何将值绑定到 class 属性?

[英]How to bind a value to a class property?

I am new to web development and new to C#/Blazor.我是 web 开发的新手,也是 C#/Blazor 的新手。

I am therefore working on a pet project of mine.因此,我正在从事我的一个宠物项目。 In this project, I have a page where I would like the user to input some numbers.在这个项目中,我有一个页面,我希望用户输入一些数字。

I would like to, dynamically, bind those values to a class and then use that class to perform calculations and display those results dynamically so that as soon as the user changes the inputs, the results get updated without the need for clicking on a "submit" button or anything like that.我想动态地将这些值绑定到 class,然后使用该 class 执行计算并动态显示这些结果,以便用户更改输入后,无需单击“提交”即可更新结果"按钮或类似的东西。 The basic idea is therefore to have a live calculator of some sort.因此,基本思想是拥有某种实时计算器。

I am using MudBlazor framework to speed things up.我正在使用 MudBlazor 框架来加快速度。 Here is my starting code located in Pages/Project.razor :这是我位于Pages/Project.razor中的起始代码:

<MudItem xs="12" sm="6" md="4">
  <MudNumericField @bind-Value="Project.NumDays" Label="Number of days" Variant="Variant.Text" Min="0" Max="10000" />
</MudItem>

@code {
  public class Project
  {
    public string NumDays // property
    { get; set; }
  }
}

Right now, the app is stating that it can't recognize the Project class.目前,该应用程序声明它无法识别项目 class。 How can I achieve what I want?我怎样才能达到我想要的? Is this possible?这可能吗? Or do I need to define the Project class outside the Pages directory?还是我需要在Pages目录之外定义Project class ?

You must instantiate the Project class... You can't use the class definition identifier as a value to the @bind-Value directive attribute.您必须实例化项目 class... 您不能使用 class 定义标识符作为@bind-Value指令属性的值。 Do that like this:这样做:

Project project = new Project();

Your code should look like this:您的代码应如下所示:

<MudItem xs="12" sm="6" md="4">
  <MudNumericField @bind-Value="project.NumDays" Label="Number of days" Variant="Variant.Text" Min="0" Max="10000" />
</MudItem>


@code {
    Project project = new Project();

  public class Project
  {
    public string NumDays { get; set; } // property
    
  }
}

Note that the Project instance starts with lowercase p请注意,项目实例以小写p开头

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM