ASP.NET Core MVC+EF Core項目實戰


項目背景

本項目參考於《Pro Entity Framework Core 2 for ASP.NET Core MVC》一書,項目內容為party邀請答復。

新建項目

本項目開發工具為VS2017,打開VS2017,新建項目,選擇ASP.NETCore Web Application,項目名為PartyInvites,點擊OK,選擇模板為MVC(為了省事)。當然為了熟悉MVC流程也可以選擇空模板自己來搭建項目結構。

項目開發

1.創建數據實體類以及數據庫上下文類
在Models文件夾下創建兩個類,DataContext和GuestResponse類,類中具體內容如下:

public class GuestResponse
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
        public bool? WillAttend { get; set; }
    }
    public class DataContext : DbContext
    {
        public DataContext(DbContextOptions<DataContext> options) : base(options)
        {

        }
        public DbSet<GuestResponse> Responses { get; set; }
    }

2.編寫Controller和View
打開Controllers文件夾下的HomeController文件(選擇空模板的同學自己創建文件夾和HomeController文件),HomeController具體代碼如下:

public class HomeController : Controller
    {
        private DataContext _dataContext;
        public HomeController(DataContext dataContext) => _dataContext = dataContext;
        public IActionResult Index() => View();
        public IActionResult Respond() => View();
        [HttpPost]
        public IActionResult Respond(GuestResponse response)
        {
            _dataContext.Responses.Add(response);
            _dataContext.SaveChanges();
            return RedirectToAction(nameof(Thanks),
                    new { Name = response.Name, WillAttend = response.WillAttend });
        }
        public IActionResult Thanks(GuestResponse response)
        {
            return View(response);
        }
        public IActionResult ListResponses() =>
                    View(_dataContext.Responses.OrderByDescending(r => r.WillAttend));
    }

修改Views/Shared文件夾下的_Layout.cshtml文件,如下:

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Party Invites</title>
    <link rel="stylesheet" href="/lib/bootstrap/dist/css/bootstrap.css" />
</head>
<body>
    <div>
        @RenderBody()
    </div>
</body>

</html>

在Home文件夾下,修改Index.cshtml,內容如下:

<div class="text-center m-4">
    <h3>We're going to have an exciting party!</h3>
    <h4>And you are invited</h4>
    <a class="btn btn-primary" asp-action="Respond">RSVP Now</a>
</div>

創建新的cshtml文件,ListResponses.cshtml,

@model IEnumerable<GuestResponse>
<h3 class="bg-primary p-2 text-white text-center">
    Here is the list of people who have
    responded
</h3>
<div class="table-responsive">
    <table class="table">
        <tr>
            <td>Name</td>
            <td>Email</td>
            <td>Phone</td>
            <td>Attending</td>
        </tr>
        @foreach (GuestResponse r in Model)
        {
            <tr>
                <td>@r.Name</td>
                <td>@r.Email</td>
                <td>@r.Phone</td>
                <td>@(r.WillAttend == true ? "Yes" : "No")</td>
            </tr>

        }
    </table>
</div>

Respond.cshtml,

@model GuestResponse
<div class="bg-primary p-2 text-white text-center">
    <h2>RSVP</h2>
</div>
<form asp-action="Respond" method="post" class="m-4">
    <div class="form-group">
        <label>Your Name</label>
        <input asp-for="Name" class="form-control" />
    </div>
    <div class="form-group">
        <label>Your Email</label>
        <input asp-for="Email" class="form-control" />
    </div>
    <div class="form-group">
        <label>Your Phone Number</label>
        <input asp-for="Phone" class="form-control" />
    </div>
    <div class="form-group">
        <label>Will You Attend?</label>
        <select asp-for="WillAttend" class="form-control">
            <option value="">Choose an option</option>
            <option value="true">Yes, I'll be there</option>
            <option value="false">No, I can't come</option>
        </select>
    </div>
    <div class="text-center">
        <button type="submit" class="btn btn-primary">Submit RSVP</button>
    </div>
</form>

Thanks.cshtml

@model GuestResponse
<div class="text-center mt-3">
    <h1>Thank you, @Model.Name!</h1>
    @if (Model.WillAttend == true)
    {
        <div>
            It's great that you're coming. The drinks are already in the fridge!
        </div>
    }
    else
    {
        <div>
            Sorry to hear that you can't make it, but thanks for letting us know.
        </div>
    }
    Click <a asp-action="ListResponses">here</a> to see who is coming.
</div>

配置EF Core

配置數據庫連接字符串,在appsettings.json文件中增加如下內容:

"ConnectionStrings": {
      "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=PartyInvites;Trusted_Connection=True;MultipleActiveResultSets=true"
    }

DefaultConnection的內容為你自己的數據庫連接字符串。
修改startup.cs內容,代碼如圖

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            //config database connect string
            string conString = Configuration["ConnectionStrings:DefaultConnection"];
            services.AddDbContext<DataContext>(options =>
            options.UseSqlServer(conString));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseDeveloperExceptionPage();
            app.UseStatusCodePages();
            app.UseStaticFiles();
            //important
            app.UseMvcWithDefaultRoute();
        }
    }

配置好后,根據新建的data Model,創建數據庫,打開nuget 控制台,在控制台中輸入add-migration加名字,如add-migration addData,執行,會自動建立migrations文件夾,並在文件夾中建立addData文件,意味創建遷移文件成功。然后輸入:update-database,數據庫就創建完成,可以去數據庫檢查下表建立是否成功。
然后就可以運行項目了。
需要注意的是,前段引用了bootstrap,需要注意bootstrap是否安裝成功以及版本問題,否則頁面可能顯示不正確。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM