Continue! The previous article, today, I'm share a example simple use Crud (Read,Insert,Update,delete) in ASP.NET MVC 5)
In the article, I will go through building way handler function is essential, because, the previous article, I have share creat way( Layout Razor,ViewStart, Connect Database) you can see here
ASP.NET MVC 5 Hello World
ASP.NET MVC 5 Create Shared Layout Razor & ViewStart
ASP.NET MVC 5 Install Bootstrap
ASP.NET MVC 5 Using DBContext Connect Database
Okay, the first, you create table Post in database, you can see the image below and set it up
Let's go,you creacle a model class name "Post.cs" in Models directory, you need set data fields of Post table
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; }
}
}
Ok, the previous article, I have create a demoEntities.css file, use connect database and excule query (insert, read,update,delete)
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);
}
}
}
Create PostController.cs in Controller directory file
- Index(): display post list (Views/Post/Index.cshtml)
- Store(): using display form add post (Views/Post/Store.cshtml)
- Edit(): using display form edit (Views/Post/Edit.cshtml)
- Delete(): action delete data post
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");
}
}
}
Views/Post/Index.cshtml
<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
@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
@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>
Top comments (0)