Asp.net core 如何将模型传输到Blazor服务器端的Razor组件?
我正在使用Blazor服务器端创建聊天室 由于接收消息和发送消息的方式不同,我制作了一个名为Asp.net core 如何将模型传输到Blazor服务器端的Razor组件?,asp.net-core,.net-core,blazor,Asp.net Core,.net Core,Blazor,我正在使用Blazor服务器端创建聊天室 由于接收消息和发送消息的方式不同,我制作了一个名为MsgModel using Microsoft.AspNetCore.Components; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BlazorApp1 { public class MsgModel: Componen
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; }
}
}
razor组件ReceiveMsg.razor
和SendMsg.razor
基于此模型
@inherits MsgModel
<h3>ReceiveMsg</h3>@MsgText
现在的问题是:在for
块中,我应该将\u MsgModel
传输到组件。同时,我还不知道如何转移它
你能帮帮我吗?谢谢。最后,我找到了一个奇怪而愚蠢的方法来解决这个问题 我将这些代码添加到
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);
}
}
}
这是多么愚蠢的方式啊
@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);
}
}
[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);
}
}
}
@foreach (Models.MsgModel _MsgModel in MsgList)
{
if (_MsgModel.GetType() == typeof(ReceiveMsg))
{
<ReceiveMsg ShowFullImage="@ShowFullImage" TransferModel="_MsgModel"></ReceiveMsg>
}
else
{
<SendMsg ShowFullImage="@ShowFullImage" TransferModel="_MsgModel"></SendMsg>
}
}