【问题标题】:How can I transfer a model to a Razor Component in Blazor server-side?如何将模型传输到 Blazor 服务器端中的 Razor 组件?
【发布时间】:2020-02-06 15:30:32
【问题描述】:

我正在使用 Blazor 服务器端创建聊天室。

由于接收消息和发送消息的风格不同,我做了一个模型,命名为MsgModel

using Microsoft.AspNetCore.Components;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BlazorApp1
{
    public class MsgModel: ComponentBase
    {
        public string MsgText { get; set; }
    }
}

剃须刀组件ReceiveMsg.razorSendMsg.razor 均基于此模型。

@inherits MsgModel
<h3>ReceiveMsg</h3>@MsgText    


 @inherits MsgModel
 <h3>SendMsg</h3>@MsgText        

index.razor,我想输入消息文本并立即显示。

@page "/"

@foreach (MsgModel _MsgModel in MsgList)
{
    if (_MsgModel.GetType() == typeof(ReceiveMsg))
    {
        <ReceiveMsg></ReceiveMsg>
    }
    else
    {
        <SendMsg></SendMsg>
    }
}
<div id="inputDiv">
    <EditForm Model="_InputMsgModel" OnValidSubmit="@SubmitText">
        <InputText @bind-Value="_InputMsgModel.MsgText" />
    </EditForm>
</div>

@code{
    protected MsgModel _InputMsgModel { get; set; } = new MsgModel();
    protected List<MsgModel> MsgList { get; set; } = new List<MsgModel>();
     protected void SubmitText()
    {
        SendMsg _SendMsg = new SendMsg();
        _SendMsg.MsgText = _InputMsgModel.MsgText;
        MsgList.Add(_SendMsg);
    }
}

现在的问题是:在for 块中,我应该将_MsgModel 转移到组件。同时,我还不知道如何转移它。

你能帮帮我吗?谢谢。

【问题讨论】:

    标签: asp.net-core .net-core blazor


    【解决方案1】:

    最后,我找到了一个奇怪而愚蠢的方法来解决这个问题。

    我将这些代码添加到MsgModel

    [Parameter]
            public MsgModel TransferModel
            {
                set
                {
                    CopyAll(value, this);
                }
            }
            private void CopyAll<T>(T source, T target)
            {
                var type = typeof(T);
                foreach (var sourceProperty in type.GetProperties())
                {
                    if (sourceProperty.Name != "TransferModel")
                    {
                        var targetProperty = type.GetProperty(sourceProperty.Name);
                        targetProperty.SetValue(target, sourceProperty.GetValue(source, null), null);
                    }
                }
            }
    

    并像这样更改for 块:

    @foreach (Models.MsgModel _MsgModel in MsgList)
        {
            if (_MsgModel.GetType() == typeof(ReceiveMsg))
            {
                <ReceiveMsg ShowFullImage="@ShowFullImage" TransferModel="_MsgModel"></ReceiveMsg>
            }
            else
            {
                <SendMsg ShowFullImage="@ShowFullImage" TransferModel="_MsgModel"></SendMsg>
            }
        }  
    

    这是多么愚蠢的方式!

    【讨论】:

      猜你喜欢
      • 2021-11-10
      • 2021-05-10
      • 2020-01-13
      • 2020-04-03
      • 1970-01-01
      • 2019-12-13
      • 1970-01-01
      • 1970-01-01
      • 2020-01-25
      相关资源
      最近更新 更多