【问题标题】:Pass values from child component (form) into parent component (where submit button located)将值从子组件(表单)传递到父组件(提交按钮所在的位置)
【发布时间】:2022-01-25 13:34:21
【问题描述】:

我已将大组件分成两部分,其中一个是子组件,另一个是父组件。然而,目前在父组件值上单击提交按钮后,以某种方式变为空,并且没有数据传递到数据库中。为什么会这样以及如何解决这个问题?

在 Record.razor.cs 中

[Parameter]
public string Title { get; set; }

[Parameter]
public string Description { get; set; }

[Parameter]
public DateTime SelectedDate { get; set; }

Record.razor:

  <Form Model="this" LabelColSpan="8" WrapperColSpan="16">
    <FormItem Label="Record title" NoStyle>
      <Input @bind-Value="@this.Title" />
    </FormItem>
    <FormItem Label="Description" NoStyle>
      <Input @bind-Value="@this.Description" />
    </FormItem>
    <FormItem Label="Date" NoStyle>
      <DatePicker @bind-Value="@this.SelectedDate" ShowTime="@true" OnChange="this.OnDateSelected" />
    </FormItem>
  </Form>

Index.razor.cs:

private DiaryRecord DiaryRecordModel { get; set; }
private bool isDialogVisible;
private DateTime SelectedDate { get; set; }

public Index()
{
  this.DiaryRecordModel = new DiaryRecord();
  this.SelectedDate = DateTime.Now;
}

Index.razor:

  <Form Model="this.DiaryRecordModel"
        OnFinish="(e) => this.OnCreateNewDiaryRecord()">
    <FormItem>
      <Record Description="@context.Description"
              SelectedDate="this.SelectedDate"
              Title="@context.Title" />
    </FormItem>
    <FormItem WrapperColOffset="8" WrapperColSpan="16">
      <Button Type="@ButtonType.Primary" HtmlType="submit">
        Submit
      </Button>
      <Button OnClick="(e)=>{this.isDialogVisible = false;}">Cancel</Button>
    </FormItem>
  </Form>

日记记录.cs

  public class DiaryRecord
  {
    public Guid Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
  }

例如,今天的日期总是传递给模型,而不是实际选择的日期(其他值不带入模型):

【问题讨论】:

    标签: c# blazor blazor-server-side blazor-webassembly


    【解决方案1】:

    首先 - 不要在表单中使用表单。只使用 Index.razor 上的那个。

    第二: 一旦你这样做了:Description="@context.Description" 你的上下文会失去与字符串发生的任何事情的连接。

    这里有两个选择。

    1] 使用two-way binding,这将导致@bind-Description="@context.Description",您还需要为Record组件内的每个属性创建EventCaller

    2](更好的一个)将您的整个模型发送到Record组件:

    [Parameter] DiaryRecord DiaryRecord {get;set;}
    
    <Input @bind-Value="@DiaryRecord.Title" />
    
    <Record DiaryRecord=this.DiaryRecordModel/>
    

    【讨论】:

    • 你是说在一个组件中有长代码而不是拆分成几个组件更好吗?顺便说一句,感谢您的解决方案,它有效!
    • 不,恰恰相反。将表单分成多个组件是正确的,但在彼此内部有多个表单不是......或者你是如何暗示我认为长代码更好?
    • 我只是在想拆分是不是正确的方法。我对 blazor 很陌生。好的,所以我基本上只是删除子表单并将 FormItems 留在那里。已将更新推送到我的仓库
    • 将在回购问题中继续!
    猜你喜欢
    • 2021-06-11
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    • 2019-03-07
    • 2021-11-27
    • 2021-11-29
    • 1970-01-01
    • 2020-02-04
    相关资源
    最近更新 更多