使用.NET MVC和Bootstrap
專案結構
HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TodoList.Models.Login;
namespace TodoList.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
public ActionResult Login(String username, String password)
{
User u = new User();
u.Username = username;
u.Password = password;
if (u.isAuth())
{
Session["LogedUserID"] = u.Username.ToString();
return Json(1, JsonRequestBehavior.AllowGet);
}
else
{
return Json(0, JsonRequestBehavior.AllowGet);
}
}
public ActionResult Logout()
{
Session.Remove("LogedUserID");
return RedirectToAction("index", "home");
}
}
}
TodoController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace TodoList.Controllers
{
public class TodoController : Controller
{
public ActionResult Index()
{
Models.TodoModel tmodel = new Models.TodoModel();
return View(tmodel.GetTodos());
}
public JsonResult ins(String value)
{
Models.TodoModel tmodel = new Models.TodoModel();
return Json(tmodel.InsTodo(value), JsonRequestBehavior.AllowGet);
}
public JsonResult del(String value)
{
Models.TodoModel tmodel = new Models.TodoModel();
return Json(tmodel.DelTodo(value), JsonRequestBehavior.AllowGet);
}
}
}
Models資料夾
User.cs
namespace TodoList.Models.Login
{
public class User
{
public string Username { get; set; } = "";
public string Password { get; set; } = "";
public bool isAuth()
{
if (Username.Equals("marco"))
if (Password.Equals("marco"))
return true;
return false;
}
}
}
Todo.cs
namespace TodoList.Models
{
public class Todo
{
public int Id { get; set; }
public string Value { get; set; }
public string Date { get; set; }
}
}
TodoModel.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace TodoList.Models
{
public class TodoModel
{
public List<Todo> GetTodos()
{
List<Todo> p = new List<Todo>();
SqlConnection sqlConnection1 =
new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["TODO"].ConnectionString);
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "SELECT * FROM TODO order by id desc";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
Todo t = new Todo();
t.Id = reader.GetInt32(0);
t.Value = reader.GetString(1);
//t.Date = reader.GetString(2);
p.Add(t);
}
sqlConnection1.Close();
return p;
}
public int InsTodo(String value)
{
SqlConnection sqlConnection1 =
new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["TODO"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into todo (value) values (@ID); SELECT SCOPE_IDENTITY() ";
cmd.Parameters.Add("@ID", SqlDbType.Text);
cmd.Parameters["@ID"].Value = value;
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
int i = 0;
try
{
i = cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
catch
{
return 0;
}
return GetLastRow();
}
private int GetLastRow()
{
SqlConnection sqlConnection1 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["TODO"].ConnectionString);
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "SELECT max(id) FROM TODO";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
int r = 0;
while (reader.Read())
{
r = reader.GetInt32(0);
}
sqlConnection1.Close();
return r;
}
private string SafeSqlLiteral(string inputSQL)
{
return inputSQL.Replace("'", "''");
}
internal object DelTodo(String value)
{
SqlConnection sqlConnection1 =
new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["TODO"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "delete todo where id = @ID";
cmd.Parameters.Add("@ID", SqlDbType.Int);
int xx = -1;
int.TryParse(value, out xx);
cmd.Parameters["@ID"].Value = xx;
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
int i = 0;
try
{
i = cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
catch
{
return 0;
}
return i;
}
}
}
Index.js
function button() {
//$(".del").hide();
del();
$("#sortable li").hover(function() {
$(this).find(".del").show();
$(this).addClass("active");
//alert($(this).attr('value'));
}, function() {
$(this).find(".del").hide();
$(this).removeClass("active");
});
}
function del() {
$(".del").click(function(event) {
// alert($(this).parent().attr('value'));
var lix = $(this).parent();
$.ajax({
type: "POST",
url: "/Todo/del",
data: "value=" + $(this).parent().attr("value"),
datatype: "html",
success: function(data) {
$(lix).hide("slow");
// $(lix).remove();
}
});
});
}
$(document).ready(function() {
del();
$(".del").hide();
$("#sortable li").hover(function() {
$(this).find(".del").show();
$(this).addClass("active");
//alert($(this).attr('value'));
}, function() {
$(this).find(".del").hide();
$(this).removeClass("active");
});
$("#insertop").keydown(function(event) {
if (event.which == 13) {
event.preventDefault();
$.ajax({
type: "POST",
url: "/Todo/ins",
data: "value=" + $("#insertop").val(),
datatype: "html",
success: function(data) {
if (data == 0) {
alert("Erorr!!");
} else {
$("#sortable").prepend("<li value='" + data + "' class='list-group-item'><button class='btn btn-warning btn-xs pull-right del'><span class='glyphicon glyphicon-trash' aria-hidden='true'></span></button>" + $("#insertop").val() + "</li>");
$("#insertop").val("");
button();
}
}
});
}
});
});
Home資料夾
Index.cshtml
@model IEnumerable<TodoList.Models.Todo>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<script>
$(document).ready(function() {
@if (Session["LogedUserID"] == null)
{
<text>
$('#login').modal('show');
</text>
}
$("#l").click(function(event) {
login();
});
$("#password").keydown(function(event) {
if (event.which == 13) {
event.preventDefault();
login();
}
});
$("#username").keydown(function(event) {
if (event.which == 13) {
event.preventDefault();
$("#password").focus();
}
});
$('#username').focus(function() {
$("#username").popover('hide');
});
$('#alert').hide();
$('#password').focus(function() {
$("#password").popover('hide');
});
});
function login() {
if ($("#username").val() == "") {
$("#username").popover({ trigger: 'manual', placement: 'bottom', html: 'true', content: '<span class="label label-danger"><span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span></span> Enter username' });
$('#username').popover('show');
return;
}
if ($("#password").val() == "") {
$("#password").popover({ trigger: 'manual', placement: 'bottom', html: 'true', content: '<span class="label label-danger"><span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span></span> Enter password' });
$('#password').popover('show');
return;
}
$.ajax({
type: "POST",
url: "/Home/Login",
data: "username=" + $("#username").val() + "&password=" + $("#password").val(),
datatype: "html",
success: function(data) {
if (data == 0) {
$('#alert').fadeIn().delay(800).fadeOut();
} else {
window.location.replace('/Home');
}
}
});
}
</script>
</head>
<body>
<div class="container-fluid">
<!-- 靜態導航欄 -->
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">BootStrap Testing</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active">
<a href="/Home">Home</a>
</li>
<li>
<a href="/Todo">Todo List</a>
</li>
</ul>
@if (Session["LogedUserID"] != null)
{
<text>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="/home/logout">LogOut</a>
</li>
</ul>
</text>
}
</div><!--/.nav-collapse -->
</div><!--/.container-fluid -->
</nav>
<div id="login" class="modal fade" data-keyboard="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<img style="height: 50px;" src="http://brighteyetea.com/assets/images/partners/bootstrap.png">
<h4 class="modal-title"></h4>
</div>
<div class="modal-body">
<div id="alert" class="alert alert-danger" role="alert">
<strong>Oh snap!</strong> Username o Password error!!!
</div>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1"><span class="glyphicon glyphicon-user" aria-hidden="true"></span></span>
<input type="text" id="username" class="form-control" placeholder="Username" aria-describedby="basic-addon1" required>
</div>
<br/>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1"><span class="glyphicon glyphicon-lock" aria-hidden="true"></span></span>
<input type="password" id="password" class="form-control" placeholder="Password" aria-describedby="basic-addon1" required>
</div>
</div>
<div class="modal-footer">
<button type="button" id="l" class="btn btn-primary"><span class="glyphicon glyphicon-log-in" aria-hidden="true"></span> Log in</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</div>
@if (Session["LogedUserID"] != null)
{
<text>
Welcome @Session["LogedUserID"].ToString()
<a href="/Home/Logout">logout</a>
</text>
}
</body>
</html>
Shared資料夾
Master.cshtml
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<style>
.disabled { cursor: default; }
#content {
margin-left: auto;
margin-right: auto;
width: 80%;
}
</style>
</head>
<body>
<ul class="nav nav-tabs">
<li role="presentation" class="active">
<a href="/Home">主頁</a>
</li>
<li role="presentation">
<a href="/Todo">待辦事項列表</a>
</li>
<li role="presentation">
<a href="#">Messages</a>
</li>
</ul>
@RenderBody()
</body>
</html>
Todo資料夾
Index.cshtml
@model IEnumerable<TodoList.Models.Todo>
@{
Layout = null;
}
@if (Session["LogedUserID"] == null)
{
Response.Redirect("~/HOME/");
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
@Scripts.Render("~/Scripts/index.js")
<style>
.disabled { cursor: default; }
#content {
margin-left: auto;
margin-right: auto;
width: 80%;
}
</style>
</head>
<body>
<div class="container-fluid">
<!-- 靜態導航欄 -->
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">BootStrap Testing</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a href="/Home">Home</a>
</li>
<li class="active">
<a href="/Todo">Todo List</a>
</li>
</ul>
@if (Session["LogedUserID"] != null)
{
<text>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="/home/logout">LogOut</a>
</li>
</ul>
</text>
}
</div><!--/.nav-collapse -->
</div><!--/.container-fluid -->
</nav>
<div class="row1">
<div class="col-md-8">
<div id="content" style="border: 0px solid red" class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Todo List</h3>
</div>
<div class="panel-body">
<form>
<div class="input-group">
<input type="text" id="insertop" class="form-control" placeholder="你今天要做什麼?" aria-describedby="basic-addon1">
<span class="input-group-btn">
<button class="btn btn-default" type="button"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span></button>
</span>
</div>
</form>
<br/>
<div class="items">
<ul id="sortable" class="list-group">
@foreach (var item in Model)
{
<li value="@Html.DisplayFor(modelItem => item.Id)" class="list-group-item items">
<button class="btn btn-warning btn-xs pull-right del">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
</button> @Html.DisplayFor(modelItem => item.Value)
</li>
}
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
執行結果如圖:
相關文章
- Spring MVC與Bootstrap基礎教程 - josdemSpringMVCboot
- .Net Core 3.0 MVC 中使用 SqlSugar ORM框架MVCSqlSugarORM框架
- 在ASP.NET Core MVC 2.2 中使用AutoMapperASP.NETMVCAPP
- ASP.NET MVC下使用AngularJs語言(七):Cookie的使用ASP.NETMVCAngularJSCookie
- Bootstrap++:bootstrap-select 使用boot
- ASP.NET MVC中使用FluentValidation驗證實體ASP.NETMVC
- ASP.NET MVC – 樣式和佈局簡介ASP.NETMVC
- ASP.NET MVC路由ASP.NETMVC路由
- ASP.NET MVC使用input標籤上傳檔案ASP.NETMVC
- 從 MVC 到使用 ASP.NET Core 6.0 的最小 APIMVCASP.NETAPI
- 微信授權(Net Mvc)MVC
- ASP.NET MVC 反射例子ASP.NETMVC反射
- ASP.NET MVC下使用AngularJs語言(六):獲取下拉選單的value和TextASP.NETMVCAngularJS
- ASP.NET MVC下使用AngularJs語言(五):ng-selectedASP.NETMVCAngularJS
- ASP.Net Core 2.2 MVC入門到基本使用系列 (五)ASP.NETMVC
- Nancy .Net 輕量級mvc框架使用(5)Routing路由方式整理NaNMVC框架路由
- ASP.NET MVC下使用AngularJs語言(一):Hello your nameASP.NETMVCAngularJS
- ASP.NET MVC下使用AngularJs語言(三):ng-optionsASP.NETMVCAngularJS
- ASP.NET MVC下使用AngularJs語言(四):$window.alertASP.NETMVCAngularJS
- ASP.NET MVC下使用AngularJs語言(八):顯示htmlASP.NETMVCAngularJSHTML
- ASP.NET Core MVC 入門到精通 - 3. 使用MediatRASP.NETMVC
- .net 開源模板引擎jntemplate 教程:基礎篇之在ASP.NET MVC中使用JntemplateASP.NETMVC
- asp.net core mvc 分頁ASP.NETMVC
- ASP.Net MVC過濾器ASP.NETMVC過濾器
- ASP.NET MVC – 安全簡介ASP.NETMVC
- ASP.NET MVC – 模型簡介ASP.NETMVC模型
- 將”ListControl”引入ASP.NET MVCASP.NETMVC
- BootStrap框架的使用boot框架
- bootstrap-fileinput 使用boot
- Bootstrap 的基本使用boot
- 【備忘】ASP.NET MVC 5 升級到 ASP.NET Core MVC 的部分變化ASP.NETMVC
- ASP.NET MVC下使用AngularJs語言(二):ng-click事件ASP.NETMVCAngularJS事件
- ASP.NET + MVC5 入門完整教程三 (上) --- 第一個 MVC 專案_lingshuangcanxue-CSDN 部落格_asp.net mvcASP.NETMVCGC
- 使用Java和Spring MVC構建Web應用JavaSpringMVCWeb
- 使用 Spring Boot 和 @WebMvcTest 測試 MVC Web ControllerSpring BootWebMVCController
- ASP.NET MVC Razor檢視引擎ASP.NETMVC
- ASP.NET MVC技能體系圖ASP.NETMVC
- .NET Core[MVC] 利用特性捕捉異常MVC