使用.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>
執行結果如圖:
相關文章
- ASP.NET MVC和AJAXASP.NETMVC
- Asp.Net MVC 使用 AjaxASP.NETMVC
- Bootstrap for MVC:Html.Bootstrap().TextBoxFor(model=>model.Name)bootMVCHTML
- ASP.NET MVC同步和非同步的使用總結ASP.NETMVC非同步
- ASP.NET MVC 4使用PagedList.Mvc分頁ASP.NETMVC
- ASP.NET MVC 使用 Datatables (1)ASP.NETMVC
- ASP.NET MVC 使用 Datatables (2)ASP.NETMVC
- ASP.NET MVC TagBuilder使用ASP.NETMVCUI
- .Net Mvc AutoMapper簡單使用MVCAPP
- netcore - MVC的ActionFilter的使用NetCoreMVCFilter
- ASP.NET MVC實踐系列11-FCKEditor和CKEditor的使用ASP.NETMVC
- netty系列之:Bootstrap,ServerBootstrap和netty中的實現NettybootServer
- Spring MVC與Bootstrap基礎教程 - josdemSpringMVCboot
- .Net Core 3.0 MVC 中使用 SqlSugar ORM框架MVCSqlSugarORM框架
- ASP.NET MVC中簡單使用AutofacASP.NETMVC
- [ASP.NET MVC 小牛之路]05 - 使用 NinjectASP.NETMVC
- [ASP.NET MVC 小牛之路]08 - Area 使用ASP.NETMVC
- 【轉】在ASP.NET MVC中,使用Bundle來打包壓縮js和cssASP.NETMVCJSCSS
- [ASP.NET MVC 小牛之路]06 - 使用 Entity FrameworkASP.NETMVCFramework
- Bootstrap++:bootstrap-select 使用boot
- Bootstrap系列 -- 1. 如何使用Bootstrapboot
- ASP.NET Core MVC 和 Visual Studio入門(五) 使用 SQL Server LocalDBASP.NETMVCSQLServer
- 使用ASP.NET MVC、Rabbit WeixinSDK和Azure快速開發部署微信後臺ASP.NETMVC
- ASP.NET MVC – 樣式和佈局簡介ASP.NETMVC
- ASP.NET MVC 5 - 查詢Details和Delete方法ASP.NETMVCAIdelete
- ASP.NET MVC概述:優點和特色一覽ASP.NETMVC
- Asp.Net Mvc使用Autofac實現依賴注入ASP.NETMVC依賴注入
- 【重典】Asp.net MVC Preview 4 中使用RenderComponentASP.NETMVCView
- ASP.NET MVC 5使用CrystalReport(水晶報表)ASP.NETMVC
- 在 ASP.NET MVC 中使用 HTTPS (SSL/TLS)ASP.NETMVCHTTPTLS
- ASP.NET MVC路由ASP.NETMVC路由
- 微信授權(Net Mvc)MVC
- ASP.NET MVC ModuleASP.NETMVC
- ASP.NET MVC TemplateASP.NETMVC
- ASP.NET MVC ErrorASP.NETMVCError
- ASP.NET MVC FilterASP.NETMVCFilter
- UpdatePanel for ASP.NET MVCASP.NETMVC
- ASP.NET MVC下使用AngularJs語言(七):Cookie的使用ASP.NETMVCAngularJSCookie