ASP.NET MVC 與 數據庫交互

今天一直在上班,因此沒法完成簡易留言簿系統(Controller層)的代碼,因此在工做之餘看了看ASP.NET MVC與數據庫,應該是比較舊的連接方式。jquery

因爲代碼比較多,因此從工程裏複製粘貼時,刪除了一些建立類時系統自動生成的代碼。代碼僅供參考。ajax

首先,在SQL Management Studio中建立一個數據庫和相應的Table。sql

例如:數據庫

1 CREATE TABLE Users(
2     [Id] [int] IDENTITY(1,1) NOT NULL,
3     [Email] [nvarchar](max) NOT NULL,
4     [NickName] [nvarchar](10) NOT NULL,
5     [Password] [nvarchar](10) NOT NULL,
6     [CreatOn] [datetime] NOT NULL,
7  )
8 
9 GO
T-SQL

而後,完成「Web-config」中的代碼:服務器

<connectionStrings>
    <add name="BbsConnection" connectionString="Data Source=服務器名稱;Initial Catalog=數據庫名稱;User ID=xx; Password=xxxxxx" providerName="System.Data.SqlClient"/>
  </connectionStrings>
Web-Config

其次,在Model層中創建一個名爲BbsContext,而且引用 System.Data, System.Data.SqlClient, System.Configuration 三個命名空間。代碼以下:ide

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

namespace MvcBBSApplication.Models
{
    public class BBSconnect
    {
        protected SqlConnection conn;

        public void OpenConnection()
        {
            conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BbsConnection"].ConnectionString);
            try
            {               
                if (conn.State.ToString()!="Open")
                {
                    conn.Open();
                }
            }
            catch (SqlException ex)
            {

                throw ex;
            }
        }

        public void CloseConnection()
        {
            try
            {
                conn.Close();                
            }
            catch (SqlException ex)
            {
                throw ex;
            }
        }


        //Insert
        public int InsertData(string sql)
        {
            int i = 0;
            try
            {
                if (conn.State.ToString()=="Open")
                {
                    SqlCommand cmd = new SqlCommand(sql, conn);
                    i = cmd.ExecuteNonQuery();
                }
                return i;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        //serach
        public DataSet List(string sql)
        {
            try
            {                
                    SqlDataAdapter da = new SqlDataAdapter();
                    da.SelectCommand = new SqlCommand(sql, conn);
                    DataSet ds = new DataSet();
                    da.Fill(ds);
                    return ds;
                
            }
            catch (Exception ex)
            {
                throw ex;
            } 
        }

        //Detail
        public DataTable Detail(string sql)
        {
            try
            {
                SqlDataAdapter da = new SqlDataAdapter(sql, conn);
                DataSet ds = new DataSet();
                da.Fill(ds);
                return ds.Tables[0];
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        //Delete
        public int Delete(string sql)
        {
            try
            {
                int result = 0;
                SqlCommand cmd = new SqlCommand(sql, conn);
                result = cmd.ExecuteNonQuery();
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
BbsConnect

接下來,在Model層創建一個Model模型 User,代碼:學習

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

namespace MvcBBSApplication.Models
{
    public class User
    {
        [Key]
        public int Id { get; set; }

        [DisplayName("UserName")]
        [Required(ErrorMessage = "Please enter the Email")]
        [DataType(DataType.EmailAddress, ErrorMessage = "Please enter the correct format")]
        public string Email { get; set; }

        [DisplayName("NickName")]
        [Required(ErrorMessage = "Please enter the NickName")]
        [MaxLength(10, ErrorMessage = "MaxLength 20 words")]
        public string NickName { get; set; }

        [DisplayName("Password")]
        [Required(ErrorMessage = "Please enter the Password")]
        [MaxLength(10, ErrorMessage = "MaxLength 10 words")]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [DisplayName("CreatOn")]
        [Required]
        public DateTime CreatOn { get; set; } 
    }
}
User

下來輪到 Controller層,在該層創建一個名爲UserController的控制器。在控制器中引用 System.Data 命名空間。代碼以下:ui

namespace MvcBBSApplication.Controllers
{
    public class UserController : Controller
    {
        BBSconnect bbs = new BBSconnect();

        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(User user)
        {
            if (ModelState.IsValid)
            {
                bbs.OpenConnection();
                string sql = "insert into Users(Email,NickName,Password,CreatOn) values('" + user.Email + "','" + user.NickName + "','" + user.Password + "','" + DateTime.Now + "')";
                int result = bbs.InsertData(sql);
                if (result > 0)
                {
                    ModelState.AddModelError("success", "ok");
                }
                else
                {
                    ModelState.AddModelError("error", "Failure");
                }
                bbs.CloseConnection();
                return RedirectToAction("Register", "User");
            }
            else
            {
                return View();
            }           
        }

        public ActionResult UserList(int id)
        {
            bbs.OpenConnection();
            DataSet ds = new DataSet();
            string sql = "SELECT * FROM USERS";
            if (id != 0)
            {
                sql = sql + " WHERE id = " + id + "";
            }            
            ds = bbs.List(sql);
            DataTable dt = ds.Tables[0];
            bbs.CloseConnection();
            return View(dt);
        }

        public ActionResult UserDetail(int id)
        {
            bbs.OpenConnection();
            string sql = "SELECT * FROM USERS WHERE ID = " + id + "";
            DataTable dt = bbs.Detail(sql);
            bbs.CloseConnection();
            return View(dt);
        }

        [HttpPost]
        public ActionResult RemoveUser(int id)
        {
            bbs.OpenConnection();
            string sql = "DELETE FROM USERS WHERE ID=" + id + "";
            int result = 0;
            if (id != 0)
            {
                result = bbs.Delete(sql);
                bbs.CloseConnection();
                return RedirectToAction("UserList", "User");
            }
            else
            {
                bbs.CloseConnection();
                return RedirectToAction("Register", "User");
            }
        }
    }
}
UserController

最後view層分別是 UserList, Register 與 UserDetail三個簡單的頁面。spa

Register頁面代碼:3d

@model MvcBBSApplication.Models.User


<h2>Register</h2>

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>User</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Email)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Email)
            @Html.ValidationMessageFor(model => model.Email)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.NickName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.NickName)
            @Html.ValidationMessageFor(model => model.NickName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Password)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Password)
            @Html.ValidationMessageFor(model => model.Password)
        </div>      

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("back to list", "UserList","User")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
Register

UserList頁面代碼:

@model System.Data.DataTable

@{
    var ajaxOption = new AjaxOptions()
    {
        OnSuccess = "RemoveUserSuccess",
        OnFailure = "RemoveUserFailure",
        Confirm = "Are you sure Remove?",
        HttpMethod = "Post"
    };
}

@section scripts{
      @Scripts.Render("~/bundles/jqueryval")
        <script>
            function RemoveUserSuccess() {
                alert('Remove Success');
                location.reload();
            }

            function RemoveUserFailure(xhr)
            {
                alert('Remove Failure:' + xhr.statue + ' ');
            }
        </script>
    }

<h2>UserList</h2>

<p>
    @Html.ActionLink("Create New", "Register","User")
</p>
<table>
    <tr>
        @foreach (System.Data.DataColumn col in Model.Columns)
        {
            <th>@col.Caption</th>
            
        }
        <th>操做</th>
    </tr>

@foreach (System.Data.DataRow row in Model.Rows) {
    <tr>
        @foreach (var cell in row.ItemArray)
        {
            <td>
                @cell.ToString()
            </td>            
        }       
        <td>
            @Html.ActionLink("Detail", "UserDetail", new { id = row["Id"] })
        </td>
        <td>
            @Ajax.ActionLink("Delete", "RemoveUser", new { id = row["Id"] },ajaxOption)
        </td>
    </tr>
}

</table>
UserList

UserDetail頁面代碼:

@model System.Data.DataTable



<h2>UserDetail</h2>

<fieldset>
    <legend>User</legend>

    <div class="display-label">
         Email
    </div>
    <div class="display-field">
        @Model.Rows[0]["Email"]
    </div>

    <div class="display-label">
         NickName
    </div>
    <div class="display-field">
        @Model.Rows[0]["NickName"]
    </div>

    <div class="display-label">
        Password
    </div>
    <div class="display-field">
        @Model.Rows[0]["Password"]
    </div>

    <div class="display-label">
         CreatOn
    </div>
    <div class="display-field">
        @Model.Rows[0]["CreatOn"]
    </div>
</fieldset>
<p>    
    @Html.ActionLink("Back to List", "UserList","User")
</p>
UserDetail

 

以上就是ASP.NET MVC 與數據庫交互的一種方式。刪除,列表,詳細頁,註冊功能均可以實現。可是搜索功能尚未實現。應該如何實現,將在後續的學習中加上。明天繼續完成簡易留言簿系統的controller層。

相關文章
相關標籤/搜索