Blazor 开发

本文介绍了如何在Razor页面中通过`@injectNavigationManager`进行页面跳转,使用`bind-Field`动态插入Progress控件,根据数据操作按钮的显示与隐藏,实现类似Ajax的异步更新,并展示了如何在表格中嵌入Timeline组件以及动态附件下载的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.跳转页面

在视图razor页面头部增加

@inject NavigationManager NavigationManager

在OnInitializedAsync()内增加

NavigationManager.NavigateTo("http://baidu.com");

2.表字段内部增加控件

<TableColumn @bind-Field="@context.complete_degree">
            <Template Context="v">
                <Progress  Value="@context.complete_degree"  Height="20"   Color="Color.Success" IsShowValue="true"></Progress>
            </Template>                      
        </TableColumn>

3.数据表格操作按钮,根据行数据信息显示和隐藏按钮,关键为IsShow="context.btn_claim_state"

<TableCellButton Size="Size.ExtraSmall" IsShow="context.btn_claim_state" Color="Color.Danger" Text="认领" OnClick="() => CreateReply(context)" />

4.类似ajax功能

前端:

Model.Entity.responsible = responsible;//赋值
            Model.Entity.Time_complete = date2.Replace("完成日期:", "");
            var obj = await WtmBlazor.Api.CallAPI("/api/Task_dl/CreateReply_tj", HttpMethodEnum.POST, Model);
            var DataJson = JObject.Parse(obj.Data);
            //await ToastService.Success("信息", DataJson["msg"].ToString(), autoHide: true);
            await ShowMessage(DataJson["msg"].ToString());
            if (DataJson["code"].ToString() == "1")
            {
                OnClose();
                var rv = await WtmBlazor.Api.CallAPI<Task_dlVM>($"/api/Task_dl/{id}");
                Model = rv.Data;
            }

后端:

[ActionDescription("CreateReply_tj")]
        [HttpPost("CreateReply_tj")]
        public IActionResult CreateReply_tj(Task_dlVM vm)
        {
            string code = "";
            string msg = "";
            string res = vm.Entity.responsible.Trim();
            string time_c = vm.Entity.Time_complete;
            string userid=   Wtm.LoginUserInfo.ITCode;
           var  t5 = _fsql.Update<Model.Task_dl>()
               .Set(a => new Model.Task_dl { 
                   responsible=res,Time_complete=time_c
                   ,btn_claim_state=false,btn_reply_state=true
               
               })//多个字段信息修改
               .Where(a => a.ID==vm.Entity.ID).ExecuteAffrows();
            if (t5 > 0)
            {
                code = "1";
                msg = "认领成功!";
            }
            else
            {
                code = "0";
                msg = "认领失败!";
            }
            return Ok(new { code=code,msg=msg });// 用 OK  JsonResult 都可以
        }

5.表字段内加控件,如timeline

<TableColumn @bind-Field="@context.complete_degree">
            <Template Context="v">
                <Progress   Value=v.Value  Height="20"   Color="Color.Success" IsShowValue="true"></Progress>
            </Template>                      
        </TableColumn>

6.时间轴

调用采取一下点击事件

private async Task OnCreateClick1(IEnumerable<TimeLine1_View> items)
    {
        if (await OpenDialog<Show>("时间轴",null,Size.Small) == DialogResult.Yes)
        {
            await dataTable.QueryAsync();
        }
    }

(1)创建展示页面 Show.razor

@page "/_Admin/TimeLine1/Show"
@using Base.ViewModel._Admin.TimeLine1VMs;
@inherits BasePage
 
@inject IStringLocalizer<BootstrapBlazor.Components.Timeline> Localizer


 <div style="height:500px;max-height:500px;overflow:auto;">
    <Timeline Items="TimelineItems1"></Timeline>
 </div> 
@code {
    private List<TimelineItem> TimelineItems1 = new List<TimelineItem>();
    protected override async Task OnInitializedAsync()
    {
        for(int i = 0; i < 21; i++)
        {
            IDictionary<string, object> parameters = new Dictionary<string, object> { { "id", i.ToString() } };
            TimelineItem t = new TimelineItem();
            if (i == 0)
            {
                t.Color = Color.Success;
            }
            t.Component = BootstrapDynamicComponent.CreateComponent<Cs>(parameters);            
            TimelineItems1.Add(t);
        }
        await base.OnInitializedAsync(); 
    }
}
(2)创建单个时间点显示内容页面  Cs.razor

@page "/_Admin/TimeLine1/Cs/{id}"
@using Base.ViewModel._Admin.TimeLine1VMs;
@using System.IO;
@inherits BasePage
@inject DownloadService DownloadService
 
<div class="div1" >
    <span >@d.ToString("yyyy-MM-dd HH:mm:ss") </span> 
    <span>发布</span> 
    <span>创建部门:***</span> 
    <span>创建人:***</span>
</div>
<div>
    测试1111
</div>
<div style="display:@isshow">
   测试
</div>
<div>
    <Button IsAsync="true" Icon="fa-solid fa-download" Text="下载全部文档" OnClickWithoutRender="DownloadPhysicalFileAsync"></Button>
</div>
<style type="text/css">
    .div1 span{
        margin-right:40px;
    }
</style>
@code {
    private DateTime d = DateTime.Now;
    private string isshow = "none";
    private TimeLine1VM Model = new TimeLine1VM();
    private ValidateForm vform { get; set; }
    [Parameter]
    public string id { get; set; }

    protected override async Task OnInitializedAsync()
    {
        int id1 = 0;
        int.TryParse(id, out id1);
        d = d.AddDays(id1);
        if (id1 % 2 != 0)
        {
            isshow = "block";
        }
        await base.OnInitializedAsync();
    }
    public void OnClose()
    {
        CloseDialog();
    }
    /// <summary>
    /// 下载文件
    /// </summary>
    /// <returns></returns>
    private async Task DownloadPhysicalFileAsync()
    {
        try
        {

//多文件下载
            for(int i = 0; i < 3; i++)
            {
                string i1 = "";
                if (i != 0) i1 = i.ToString();
                string filePath = System.Environment.CurrentDirectory + "\\..\\Base.Shared\\wwwroot\\images\\logo"+i1+".png";
                await using var stream = File.OpenRead(filePath);
                await DownloadService.DownloadFromStreamAsync(filePath, stream);
            }           
        }
        catch (FileNotFoundException msg)
        {
             
        }
    }
}
7.时间轴中动态附件下载

div下

<div>
        @{
            for(int i1 = 0; i1 < files.Count; i1++)
            {
                string t = files[i1].name;
                string id = files[i1].id;
                string icon = files[i1].icon;
                <Button ButtonStyle="ButtonStyle.Round" Color="Color.Light" Icon="@icon" Text="@t" OnClick="@(() => DownloadPhysicalFileAsync1(id))" style="margin-right:10px;color:black;"></Button>
            }
        }
    </div> 

code下:

class file
    {
        public string file_type { get; set; }
        public string name { get; set; }
        public string icon{ get; set; }
        public string id { get; set; }
    }
    List<file> files = new List<file>();

OnInitializedAsync方法 下

///追加下载文件的集合
        file f1 = new file();
        f1.file_type = "xls";
        f1.icon = "fas fa-file-excel";
        f1.name = "测试1.xls";
        f1.id = "0";
        files.Add(f1);

        f1 = new file();
        f1.file_type = "doc";
        f1.icon = "fas fa-file-word";
        f1.name = "测试1.doc";
        f1.id = "1";
        files.Add(f1);

        f1 = new file();
        f1.file_type = "zip";
        f1.icon = "fas fa-file-zipper";
        f1.name = "测试1.zip";
        f1.id = "2";
        files.Add(f1);

/// <summary>
    /// 动态参数下载
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    private async Task DownloadPhysicalFileAsync1(string id)
    {
        try
        {
            string i1 = "";
            if(id=="" || id=="0"){
            }
            else
            {
                i1 = id.ToString();
            }
            string filePath = System.Environment.CurrentDirectory + "\\..\\Base.Shared\\wwwroot\\images\\logo" + i1 + ".png";
            await using var stream = File.OpenRead(filePath);
            await DownloadService.DownloadFromStreamAsync(filePath, stream);
        }
        catch (FileNotFoundException msg)
        {
        }
    }

### 关于 Blazor 开发框架的使用指南 Blazor 是一种基于 .NET 的现代 Web 开发框架,允许开发者使用 C# 和 Razor 语法构建交互式的客户端和服务器端应用。以下是关于 Blazor 开发框架的学习资料、文档以及使用方法的一些详细介绍。 #### 学习资源与文档 对于初学者来说,可以从官方文档入手,这是最权威且全面的信息来源之一。Microsoft 提供了详细的 [Blazor 官方文档](https://docs.microsoft.com/aspnet/core/blazor/),涵盖了从基础到高级的各种主题[^3]。此外,还有一些社区贡献的内容可以帮助更深入地理解 Blazor: - **Blazor 组件基础知识** 如果你是初次接触 Blazor,建议先阅读一份针对新手的入门指南,例如《Blazor 组件的初学者指南》[^1]。这份材料通过简单易懂的例子介绍了如何创建并使用 Blazor 组件,帮助你快速掌握核心概念。 - **进阶功能探索** 随着技能的增长,你可以进一步研究像 `Blazor Extensions Canvas` 这样的第三方库。该工具包使得在 Blazor 中处理复杂图形变得更加容易[^2]。它特别适合那些希望在其项目里加入动态视觉效果或者游戏开发场景的人群。 #### 创建第一个 Blazor 应用程序 为了更好地实践所学理论知识,下面展示了一个简单的例子来说明如何设置一个新的 Blazor WebAssembly App 并运行起来: ```bash dotnet new blazorwasm -o MyFirstBlazorApp cd MyFirstBlazorApp dotnet run ``` 这段命令会生成一个标准模板化的 Blazor WASM (Web Assembly) 工程目录,并启动本地调试服务让你可以直接访问 http://localhost:5000 查看成果页面[^3]。 #### 示例代码解析 每一个 Blazor 组件通常由两部分构成——视图(View)与控制器(Controller),分别对应 `.razor` 文件中的 HTML/CSS 结构描述及其背后业务逻辑实现(.cs文件)[^3]: ```csharp @page "/counter" <h1>Counter</h1> <p>Current count: @currentCount</p> <button class="btn btn-primary" @onclick="IncrementCount">Click me</button> @code { private int currentCount = 0; private void IncrementCount() { currentCount++; } } ``` 上面展示了计数器组件的工作原理:当点击按钮时调用 `IncrementCount()` 方法更新状态变量 `currentCount` ,从而触发 UI 刷新显示最新数值变化情况。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值