개발환경
- Visual Studio Community 2017
- ASP.NET Core 2.2
게시판 리스트 출력
Controller
public class NoteController : Controller
{
public IActionResult Index()
{
if (HttpContext.Session.GetInt32("USER_LOGIN_KEY") == null)
{
return RedirectToAction("Login", "Account");
}
using (var db = new AspnetNoteDbContext())
{
var list = db.Notes.ToList();
return View(list);
}
}
}
View
<table class="table table-bordered">
<thead>
<tr>
<th>번호</th>
<th>제목</th>
<th>작성자</th>
</tr>
</thead>
<tbody>
@foreach (var note in Model)
{
<tr>
<td>@note.NoteNo</td>
<td>@note.NoteTitle</td>
<td>@note.UserNo</td>
</tr>
}
</tbody>
</table>
<div align="right"><a class="btn btn-danger" asp-controller="Note" asp-action="Add">글쓰기</a></div>
실행화면
게시판 게시물 추가하기
View
@model AspnetNote.MVC6.Models.Note
<div class="row">
<div class="col-lg-2"> </div>
<div class="col-lg-8">
<form class="form-horizontal" method="post" asp-controller="Note" asp-action="Add">
<div class="text-danger" asp-validation-summary="ModelOnly"> </div>
<div class="form-group">
<label>제목</label>
<input type="text" class="form-control" asp-for="NoteTitle" placeholder="제목입력" />
<span class="text-danger" asp-validation-for="NoteTitle"></span>
</div>
<div class="form-group">
<textarea class="form-control editor" rows="20" asp-for="NoteContents" placeholder="내용 입력"></textarea>
<span class="text-danger" asp-validation-for="NoteContents"></span>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">저장</button>
<a class="btn btn-default" asp-controller="Note" asp-action="Index">취소</a>
</div>
</form>
</div>
<div class="col-lg-2"> </div>
</div>
Controller
using System.Linq;
using AspnetNote.MVC6.DataContext;
using AspnetNote.MVC6.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace AspnetNote.MVC6.Controllers
{
public class NoteController : Controller
{
public IActionResult Add()
{
return View();
}
[HttpPost]
public IActionResult Add(Note model)
{
if (HttpContext.Session.GetInt32("USER_LOGIN_KEY") == null)
{
return RedirectToAction("Login", "Account");
}
model.UserNo =int.Parse(HttpContext.Session.GetInt32("USER_LOGIN_KEY").ToString());
if (ModelState.IsValid)
{
using (var db = new AspnetNoteDbContext())
{
db.Notes.Add(model);
if (db.SaveChanges() > 0)
{
return Redirect("Index");
}
ModelState.AddModelError(string.Empty, "게시물을 저장 할 수 없습니다.");
}
}
return View(model);
}
}
참조