当前位置: 移动技术网 > IT编程>开发语言>.net > Blazor一个简单的示例让我们来起飞

Blazor一个简单的示例让我们来起飞

2020年05月06日  | 移动技术网IT编程  | 我要评论

贝因美积分兑换,癫马女郎之一夜情,盛世才家族血案真相

blazor

blazor他是一个开源的web框架,不,这不是重点,重点是它可以使c#开发在浏览器上运行web应用程序.它其实也简化了spa的开发过程.

blazor = browser + razor

为什么选择blazor?

blazor可以让.net附有全栈开发功能,它可以使web开发变得轻松而高效.而且blazor是开源的,它得到了社区的大力支持,而且发展速度会很快.

它还拥有spa的一些功能比如:

  • 路由
  • 依赖注入
  • 服务端渲染
  • layout
    等等

创建应用

如果说无法在看到blazor webassembly app那么执行如下命令即可.

dotnet new -i microsoft.aspnetcore.components.webassembly.templates::3.2.0-preview5.20216.8

项目结构如下所示

我们可以看到上图中的项目结构

  • blazorservercrudsample.client:该项目工程中包含了客户端的相关代码页面等文件
  • blazorservercrudsample.server:该项目工程中包含了webapi.
  • blazorservercrudsample.shared:该类库中用于存放客户端和服务端之间的共享代码.

blazorservercrudsample.server

控制器代码如下所示

    [route("api/[controller]")]
    public class studentcontroller : controller
    {
        private readonly shared.data.appcontext _dbcontext;

        public studentcontroller(shared.data.appcontext dbcontext)
        {
            this._dbcontext = dbcontext;
        }
        [httpget]
        public async task<list<student>> get()
        {
            return await _dbcontext.students.asqueryable().tolistasync();
        }
        [httpget("{id}")]
        public async task<student> get(int id)
        {
            return await _dbcontext.students.findasync(id);
        }
        [httppost]
        public async task post([frombody] student student)
        {
            student.createtime = datetime.now;
            if (modelstate.isvalid)
                await _dbcontext.addasync(student);
           await _dbcontext.savechangesasync();
        }
        [httpput]
        public void put([frombody] student student)
        {
            if (modelstate.isvalid)
                _dbcontext.update(student);
            _dbcontext.savechanges();
        }
        [httpdelete("delete/{id}")]
        public void delete(int id)
        {
            var entity = _dbcontext.students.find(id);
            _dbcontext.students.remove(entity);
            _dbcontext.savechanges();
        }



    }
    public class program
    {
        public static void main(string[] args)
        {
            buildwebhost(args).run();
        }

        public static iwebhost buildwebhost(string[] args) =>
            webhost.createdefaultbuilder(args)
                .useconfiguration(new configurationbuilder()
                    .addcommandline(args)
                    .build())
                .usestartup<startup>()
                .build();
    }

对于startup类,我们可以看到在开发模式下,启动blazor调试,并且我们可以看到我们通过useclientsideblazorfiles来启动我们的客户端startup

    public class startup
    {
        public startup(iconfiguration configuration)
        {
            configuration = configuration;
        }

        public iconfiguration configuration { get; }

        public void configureservices(iservicecollection services)
        {
            services.addcontrollers();
            services.addresponsecompression();
            services.adddbcontext<appcontext>(options =>
            {
                options.usesqlserver("data source=.;initial catalog=blazorservercrudsample;user id=sa;password=sa;multipleactiveresultsets=true;");
            });
        }

        // this method gets called by the runtime. use this method to configure the http request pipeline.
        public void configure(iapplicationbuilder app, iwebhostenvironment env)
        {
            app.useresponsecompression();

            if (env.isdevelopment())
            {
                app.usedeveloperexceptionpage();
                app.useblazordebugging();
            }

            app.usestaticfiles();
            app.useclientsideblazorfiles<client.startup>();

            app.userouting();

            app.useendpoints(endpoints =>
            {
                endpoints.mapdefaultcontrollerroute();
                endpoints.mapfallbacktoclientsideblazor<client.startup>("");
            });
        }
    }

blazorservercrudsample.client

如下所示我创建了一个列表页面,在代码中我们可以看到@page他定义了该页面的url,当然在razor中也是这样的,而且下最下面我通过httpclient进行我们的api调用,在这 system.net.http.json这篇文章中我们也可以看到他简直就是为了我们blazor而生的大大减少了我们的代码量.

而且在我的代码中最后一部分有一个@functions片段,它包含了页面所有的业务逻辑,在我们页面初始化时我们通过oninitializedasync方法进行调用我们的api然后将其进行填充赋值并填充到我们的html中.

@page "/fetchstudent"
@inject httpclient http
@using blazorservercrudsample.shared.models

    <h1>students</h1>
<p>
    <a href="/addstudent">create new</a>
</p>
@if (students == null)
{
    <p><em>loading...</em></p>
}
else
{
    <table class='table'>
        <thead>
            <tr>
                <th>id</th>
                <th>name</th>
                <th>description</th>
                <th>createtime</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var student in students)
            {
                <tr>
                    <td>@student.id</td>
                    <td>@student.name</td>
                    <td>@student.description</td>
                    <td>@student.createtime</td>
                        <td>
                            <a href='/editstudent/@student.id'>edit</a>  |
                            <a href='/delete/@student.id'>delete</a>
                        </td>
                </tr>

            }
        </tbody>
    </table>
}

@functions {
    student[] students;
    protected override async task oninitializedasync()
    {
        students = await http.getjsonasync<student[]>("api/student");
    }
}  

如下代码中我们还是对我们的页面提供了url,其中id是将从url中的参数传递到我们的@functions代码中,在id上面指定 [parameter] 属性,该属性指定的就是url中的参数值.在这我们通过使用 @bind 来将我们的html组件和类对象进行双向绑定.

@page "/editstudent/{id}"
@inject httpclient http
@using blazorservercrudsample.shared.models
@inject microsoft.aspnetcore.components.navigationmanager navigation

    <h2>edit student</h2>
<hr />
<div class="row">
    <div class="col-md-4">
        <form @onsubmit="@(async () => await updatestudent())">
            <div class="form-group">
                <label for="name" class="control-label">name</label>
                <input for="name" class="form-control" @bind="@student.name" />
            </div>
            <div class="form-group">
                <label asp-for="description" class="control-label">description</label>
                <textarea asp-for="description" class="form-control" @bind="@student.description"> </textarea>
            </div>
            <div class="form-group">
                <input type="submit" value="save" class="btn btn-primary" />
                <input type="submit" value="cancel" @onclick="@cancel" class="btn btn-warning" />
            </div>
        </form>
    </div>
</div>

@functions {
    [parameter]
    public string id { get; set; }
    public student student = new student();
    protected override async task oninitializedasync()
    {
        student = await http.getjsonasync<student>("/api/student/" + convert.toint32(id));
    }
    protected async task updatestudent()
    {
        await http.sendjsonasync(httpmethod.put, "api/student", student);
        navigation.navigateto("/fetchstudent");
    }
    void cancel()
    {
         navigation.navigateto("/fetchstudent");
    }
}  

在configureservices方法中,可以在依赖项注入容器中注册本地服务。

   public class startup
    {
        public void configureservices(iservicecollection services)
        {
        }

        public void configure(icomponentsapplicationbuilder app)
        {
            app.addcomponent<app>("app");
        }
    }

blazorwebassemblyhost可以用于在di容器中定义接口和实现。

    public class program
    {
        public static void main(string[] args)
        {
            createhostbuilder(args).build().run();
        }

        public static iwebassemblyhostbuilder createhostbuilder(string[] args) =>
            blazorwebassemblyhost.createdefaultbuilder()
                .useblazorstartup<startup>();
    }

blazor可以基于服务端运行但是需要注意服务端的话需要为每一个客户端打开连接,并且我们必须一直与服务端保持连接才行.如果说切换到webassembly客户端版本,限制是完全不同的,但是目前来说的话他首次需要下载一些运行时文件到浏览器中.

通过如上代码我们可以看到一个简单的blazor应用程序的建立,详细代码的话大家可以看一下github仓库中的内容.通过源码的话直接启动blazorservercrudsample.server即可,希望可以通过本示例帮助到你~共同学习共同进步.

reference

https://github.com/hueifeng/blazorcrudsample

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网