STEM STUDY

Nghiên cứu & phát triển (R&D) về các lĩnh vực IoT, Robotics, Trí tuệ nhân tạo (AI), 3D Printing, ứng dụng website và các ứng dụng di động. Website: http://www.itr.com.vn

22. March 2020 13:57
by ĐÀO TƯỜNG SƠ
1 Comments

Asp.net MVC 0011 - Code First with CRUD Bootstrap Modal

22. March 2020 13:57 by ĐÀO TƯỜNG SƠ | 1 Comments

Bước 1: Tạo Model với tên Book

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCTest07.Models
{
    public class Book
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Author { get; set; }
        public decimal Price { get; set; }
        public DateTime Published { get; set; }
    }
}

Bước 2: Cài đặt Entity Framework

- Vào Tool/NuGet Pakage Manager/Manage NuGet Package for Solution... và cài đặt Entity Framework.

Bước 3: Tạo thư mục Context và lớp BookContext

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace MVCTest07.Context
{
    public class BookContext:DbContext
    {
        public DbSet<Book> Books { get; set; }
    }
}

Bước 4: Tạo chuỗi kết nối trong web.config

<connectionStrings>
    <add name="BookContext" connectionString="Data Source=DAOTUONGSO\SQLEXPRESS; Initial Catalog=LibraryDB2155;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

Bước 5: Tạo Controller với lựa chọn Entity Framework

Bước 6: Hiệu chỉnh view Index

@model IEnumerable<MVCTest07.Models.Book>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<table>
    <tr>
        <td><a href='@Url.Action("Create","Books")' class="pull-right btn mauxanh btn-create"><i class="glyphicon glyphicon-plus"></i> New</a></td>
    </tr>
</table>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Author)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Price)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Published)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Author)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Price)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Published)
            </td>
            <td>
                <a href='@Url.Action("Edit", "Books", routeValues: new { id=item.Id})' class="btn btn-xs mauvang btn-edit"><i class="glyphicon glyphicon-pencil"></i></a> <a href='@Url.Action("Delete", "Books", routeValues: new { id=item.Id})' class="btn btn-xs maudo btn-delete"><i class="glyphicon glyphicon-trash"></i></a> </td> </tr> } </table> <!-- Modal Create--> <div class="modal fade" id="myModalcreate" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <!-- modal content --> ... </div> </div> <script> $(document).ready(function () { $('.btn-create').click(function (e) { e.preventDefault(); var $modal = $('#myModalcreate'); var $modalDialog = $('.modal-dialog'); var href = $(this).prop('href'); // không cho phép tắt modal khi click bên ngoài modal var option = { backdrop: 'static' }; // load modal $modalDialog.load(href, function () { $modal.modal(option, 'show'); }); }); }); </script> <!-- Modal Edit--> <div class="modal fade" id="myModaledit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <!-- modal content --> ... </div> </div> <script> $(document).ready(function () { $('.btn-edit').click(function (e) { e.preventDefault(); var $modal = $('#myModaledit'); var $modalDialog = $('.modal-dialog'); var href = $(this).prop('href'); // không cho phép tắt modal khi click bên ngoài modal var option = { backdrop: 'static' }; // load modal $modalDialog.load(href, function () { $modal.modal(option, 'show'); }); }); }); </script> <!-- Modal Delete--> <div class="modal fade" id="myModaldelete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <!-- modal content --> ... </div> </div> <script> $(document).ready(function () { $('.btn-delete').click(function (e) { e.preventDefault(); var $modal = $('#myModaldelete'); var $modalDialog = $('.modal-dialog'); var href = $(this).prop('href'); // không cho phép tắt modal khi click bên ngoài modal var option = { backdrop: 'static' }; // load modal $modalDialog.load(href, function () { $modal.modal(option, 'show'); }); }); }); </script>

Bước 7: Hiệu chỉnh Controller

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using MVCCodeFirst.Context;
using MVCCodeFirst.Models;

namespace MVCCodeFirst.Controllers
{
    public class BooksController : Controller
    {
        private BookContext db = new BookContext();

        // GET: Books
        public ActionResult Index()
        {
            return View(db.Books.ToList());
        }

        // GET: Books/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Book book = db.Books.Find(id);
            if (book == null)
            {
                return HttpNotFound();
            }
            return View(book);
        }

        // GET: Books/Create
        public ActionResult Create()
        {
            return PartialView();
        }

        // POST: Books/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,Name,Author,Price,Published")] Book book)
        {
            if (ModelState.IsValid)
            {
                db.Books.Add(book);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(book);
        }

        // GET: Books/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Book book = db.Books.Find(id);
            if (book == null)
            {
                return HttpNotFound();
            }
            return PartialView(book);
        }

        // POST: Books/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,Name,Author,Price,Published")] Book book)
        {
            if (ModelState.IsValid)
            {
                db.Entry(book).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(book);
        }

        // GET: Books/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Book book = db.Books.Find(id);
            if (book == null)
            {
                return HttpNotFound();
            }
            return PartialView(book);
        }

        // POST: Books/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Book book = db.Books.Find(id);
            db.Books.Remove(book);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

Bước 8: Hiệu chỉnh view Create, Edite và Delete

//Hiệu chỉnh view Create

@model MVCCodeFirst.Models.Book

@{
    ViewBag.Title = "Create";
}

@using (Html.BeginForm("Create", "Books", FormMethod.Post, htmlAttributes: new { @class = "form-create" }))
{
    @Html.AntiForgeryToken()

    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
            <h4 class="modal-title" id="myModalLabel">Add Item</h4>
        </div>

        <div class="modal-body">
            <div class="form-horizontal">
                <h4>Book</h4>
                <hr />
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                <div class="form-group">
                    @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.Author, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Author, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Author, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.Price, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Price, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Price, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.Published, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Published, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Published, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <input type="submit" value="Create" class="btn btn-default" />
                    </div>
                </div>
            </div>
        </div>

        <div class="modal-footer">
            <button type="submit" class="btn mauxanh"><i class="glyphicon glyphicon-floppy-save"></i> Add</button>
            <button type="button" class="btn mauxam" data-dismiss="modal"><i class="glyphicon glyphicon-remove"></i> Close</button>
        </div>
    </div>
}

//Hiệu chỉnh view Edit

@model MVCCodeFirst.Models.Book

@{
    ViewBag.Title = "Edit";
}

@using (Html.BeginForm("Edit", "Books", FormMethod.Post, htmlAttributes: new { @class = "form-edit" }))
{
    @Html.AntiForgeryToken()

    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
            <h4 class="modal-title" id="myModalLabel">Edit Item</h4>
        </div>

        <div class="modal-body">
            <div class="form-horizontal">
                <h4>Book</h4>
                <hr />
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                @Html.HiddenFor(model => model.Id)

                <div class="form-group">
                    @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.Author, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Author, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Author, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.Price, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Price, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Price, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.Published, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Published, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Published, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <input type="submit" value="Save" class="btn btn-default" />
                    </div>
                </div>
            </div>
        </div>

        <div class="modal-footer">
            <button type="submit" class="btn mauxanh"><i class="glyphicon glyphicon-floppy-save"></i> Update</button>
            <button type="button" class="btn mauxam" data-dismiss="modal"><i class="glyphicon glyphicon-remove"></i> Close</button>
        </div>
    </div>
}


//Hiệu chỉnh view Delete

@model MVCCodeFirst.Models.Book

@{
    ViewBag.Title = "Delete";
}
@using (Html.BeginForm("Delete", "Books", FormMethod.Post, htmlAttributes: new { @class = "form-create" }))
{
    @Html.AntiForgeryToken()

    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
            <h4 class="modal-title" id="myModalLabel">Delete Item</h4>
        </div>

        <div class="modal-body">
            <h3>Are you sure you want to delete this?</h3>
        </div>

        <div class="modal-footer">
            <button type="submit" class="btn mauxanh"><i class="glyphicon glyphicon-floppy-save"></i> Delete</button>
            <button type="button" class="btn mauxam" data-dismiss="modal"><i class="glyphicon glyphicon-remove"></i> Close</button>
        </div>
    </div>
}


 

Comments (1) -

Acabei de conhecer seu weblog e quero ler muito texto. Você trabalha bastante bem na rede e sabe bem como colocar a palavra no lugar correto.

Aw, this was a very good post. Finding the time and actual effort to create a good article… but what can I say… I hesitate a whole lot and don't seem to get anything done.

@jefferson: May be your version bootstrap is 4.x or up. This article using bootstrap 3.xx

fantastic put up, very informative. I ponder why the opposite experts of this sector don't understand this. You must continue your writing. I am confident, you've a great readers' base already!  Feel free to surf to my homepage -  Essay Writing service - www.Johnsonclassifieds.com/user/profile/3783009

What's up to all, since I am genuinely keen of reading this webpage's post to be updated regularly. It includes good stuff.  Here is my site ::  Danuta - wwme-tv.com/.../netsoltrademark.php

Hey, I think your site might be having browser compatibility issues. When I look at your blog in Chrome, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, fantastic blog!

I was wondering if you ever considered changing the layout of your blog? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having 1 or 2 pictures. Maybe you could space it out better?  My site  write My essay - www.nutritionqualityindex.net/.../...trademark.php

What's up friends, how is the whole thing, and what you wish for to say on the topic of this post, in my view its truly awesome in favor of me.  my web-site ...  Essay Writing Service - Stroneks.ru/.../redirect.php://Writemyessaytoday.org/write-my-term-paper

Hey there,  You have done a fantastic job. I'll definitely digg it and personally suggest to my friends. I am confident they will be benefited from this web site.  My web-site  Adelaida - schoolnewsnetwork.biz/.../netsoltrademark.php

Hello, its fastidious article regarding media print, we all know media is a wonderful source of facts.  Feel free to surf to my web site -  essay Writer - http://Kosmetika-optom.kz/otzyvy.html

Pretty element of content. I just stumbled upon your website and in accession capital to claim that I get actually enjoyed account your blog posts. Any way I will be subscribing for your feeds or even I fulfillment you get right of entry to consistently rapidly.  My web-site -  Write My Essay - Www.arcadeprehacks.com/.../92116-bebasikkk

Add comment