ASP.NET MVC 5 CRUD Tutorial With Example For Beginners

Tiếp tục với các bài viết chia sẻ trước, nay mình làm một ví dụ đơn giản về các tính năng (Read,Insert,Update,Delete) in ASP.NET MVC 5
Trong nội dung bài này mình sẽ đi qua cách xây dựng các hàm xử lý là chủ yếu, vì những bài trước mình đã chia sẻ với mọi người rồi, từ cách tạo (Layout Razor, ViewStart,Connect Database) mọi người có thể xem lại các bài viết trước dưới đây

Okay, Đầu tiên mình tạo một table Posts trong Database của mình, bạn có thể xem hình dưới đây và thiết lập nó

ASP.NET MVC 5 CRUD Tutorial With Example For BeginnersTiếp tục mình tạo một lớp Model tên là Post.cs trong thư mục Models, dùng để thiết lập các trường dữ liệu của table Posts nhé mọi người

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace MVC5_HelloWorld.Models
{
    public class Post
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Body { get; set; }
        [DataType(DataType.Date), DisplayFormat(DataFormatString = @"{0:dd\/MM\/yyyy HH:mm}",
            ApplyFormatInEditMode = true)]
        public DateTime Created_at { get; set; }
        [DataType(DataType.Date), DisplayFormat(DataFormatString = @"{0:dd\/MM\/yyyy HH:mm}",
            ApplyFormatInEditMode = true)]
        public DateTime Updated_at { get; set; }
    }
}

Các bạn xem lại bài trước để tạo file demoEntities.cs dùng để kết nối đến database, để chúng ta có thể thực hiện các câu lệnh truy vấn (Read,Insert,Update, Delete) trong LinQ nhé

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MVC5_HelloWorld.Models;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace MVC5_HelloWorld.Models
{
    public class demoEntities : DbContext
    {
        public demoEntities() : base("demoASPEntities")
        {
        }
        public DbSet<User> Users { get; set; }

        public DbSet<Post> Posts { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //Database.SetInitializer<demoEntities>(null);
            modelBuilder.Entity<User>().ToTable("Users");
            modelBuilder.Entity<Post>().ToTable("Posts");
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

            base.OnModelCreating(modelBuilder);


        }
    }
}

Sau khi connect database ok, bạn tiến hành tạo file PostController.cs trong thư mục Controllers trong file này mình tạo một số hàm như sau
+ Index(): dùng hiển thị danh sách post (Views/Post/Index.cshtml)
+ Store(): dùng để hiện thị form add và thao tác insert post (Views/Post/Store.cshtml)
+ Edit(): dùng hiển thị form edit và thao tác update (Views/Post/Edit.cshtml)
+ Delete(): dùng thực hiện thao tác delete 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC5_HelloWorld.Models;
using System.Data.Entity;
namespace MVC5_HelloWorld.Controllers
{
    public class PostController : Controller
    {
        private demoEntities _db = new demoEntities();
        public ActionResult Index()
        {
            var data = (from s in _db.Posts select s).ToList();
            ViewBag.posts = data;
            return View();
        }

     
        public ActionResult Store()
        {
            return View();
        }


        [HttpPost]
        public ActionResult Store(Post _post)
        {
            if (ModelState.IsValid)
            {
                var title = _post.Title;
                var count = _db.Posts.Where(s => s.Title.Contains(title)).Count();
                if (count > 0)
                {
                    ViewBag.message = "Title already exists";
                    return View();
                }
                _post.Created_at = DateTime.Now;
                _post.Updated_at = DateTime.Now;
                  _db.Posts.Add(_post);
                 _db.SaveChanges();
                 return RedirectToAction("Index");

                //return Json(_post);
            }
            ViewBag.message = "Insert failed!";
            return View();
           
        }

        public ActionResult Edit(int id)
        {
            var data = _db.Posts.Where(s => s.Id==id).FirstOrDefault();      
            return View(data);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,Title,Body,Updated_at")] Post _post)
        {

            if (ModelState.IsValid)
            {
                var data = _db.Posts.Find(_post.Id);
                 data.Title = _post.Title;
                 data.Body = _post.Body;
                 data.Updated_at = DateTime.Now;
                 _db.Entry(data).State = EntityState.Modified;
                 _db.SaveChanges();
               // return Json(_post);
                return RedirectToAction("Index");
            }
            var dataEdit = _db.Posts.Where(s => s.Id == _post.Id).FirstOrDefault();
            return View(dataEdit);
        }

        [HttpGet]
        public ActionResult Delete(int? id)
        {
            var product = _db.Posts.Where(s => s.Id == id).First();
            _db.Posts.Remove(product);
            _db.SaveChanges();
            return RedirectToAction("Index");
        }
    }

    
}

Chúng ta đã cài đặt các phương thức và hàm xong cho việc xử lý, giờ ta cần tạo giao diện form thôi

Views/Post/Index.cshtml : dùng hiển thị danh sách post

<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-10">
            <div class="card">
                <div class="card-header">
                    List Posts
                   <a href="@Url.Action("Store", "Post")" class="btn btn-success">Add</a>
                </div>
                <div class="card-body">
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th>STT</th>
                                <th>Title</th>
                                <th>Body</th>
                                <th>Created_at</th>
                                <th>Updated_at</th>
                                <th>Edit</th>
                                <th>Delete</th>
                            </tr>
                        </thead>
                        <tbody>
                            @{ 
                                int i = 1;
                            }
                            @foreach(var post in ViewBag.Posts) {
                            
                            <tr>
                                <td>@i</td>
                                <td>@post.Title</td>
                                <td>@post.Body</td>
                                <td>@post.Created_at</td>
                                <td>@post.Updated_at</td>
                                <td><a href="@Url.Action("Edit","Post",new {id=post.Id})" class="badge badge-warning">Modify</a></td>
                                <td><a href="@Url.Action("Delete","Post",new {id=post.Id})" class="badge badge-danger">Remove</a></td>
                            </tr>
                                i++;
                            }
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

Views/Post/Store.cshtml :  Dùng hiển thị Form thêm Post

@model MVC5_HelloWorld.Models.Post
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">
                    Add Post
                </div>
                <div class="card-body">
                    @using (Html.BeginForm("Store", "Post", FormMethod.Post))
                    {
                        <div class="form-group">
                            <label>Title</label>
                            @Html.TextBoxFor(m => m.Title, new { @class = "form-control", @placeholder = "Title" })
                        </div>
                        <div class="form-group">
                            <label>Body</label>
                            @Html.TextBoxFor(m => m.Body, new { @class = "form-control", @placeholder = "body" })
                        </div>
                        <div class="form-group">
                            <input type="submit" name="submit" value="Add Post" class="btn btn-success" />
                            @if (ViewBag.message != "")
                            {
                                <span class="badge badge-danger">@ViewBag.message</span>
                            }
                        </div>
                    }
                </div>
            </div>
        </div>
    </div>
</div>

Views/Post/Edit.cshtml : Dùng hiển thị dữ liệu cần chỉnh sửa

@model MVC5_HelloWorld.Models.Post
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">
                    Edit Post
                </div>
                <div class="card-body">
                    @using (Html.BeginForm("Edit", "Post", FormMethod.Post))
                    {@Html.AntiForgeryToken()
                    @Html.HiddenFor(m=>m.Id)
                    <div class="form-group">
                        <label>Title</label>
                        @Html.TextBoxFor(m => m.Title, new { @class = "form-control" })
                    </div>
                    <div class="form-group">
                        <label>Body</label>
                        @Html.TextBoxFor(m => m.Body, new { @class = "form-control" })
                    </div>
                    <div class="form-group">
                        <input type="submit" name="submit" value="Update" class="btn btn-success" />
                        @if (ViewBag.message != "")
                        {
                            <span class="badge badge-danger">@ViewBag.message</span>
                        }
                    </div>
                }
                </div>
            </div>
        </div>
    </div>
</div>

Okay vậy là xong giờ ta có thể demo thử:

ASP.NET MVC 5 CRUD Tutorial With Example For BeginnersASP.NET MVC 5 CRUD Tutorial With Example For BeginnersASP.NET MVC 5 CRUD Tutorial With Example For Beginners

Vậy là ok rồi !

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)