zoukankan      html  css  js  c++  java
  • ASP.NET MVC 与 数据库交互

    今天一直在上班,所以无法完成简易留言簿系统(Controller层)的代码,所以在工作之余看了看ASP.NET MVC与数据库,应该是比较旧的链接方式。

    由于代码比较多,所以从工程里复制粘贴时,删除了一些创建类时系统自动生成的代码。代码仅供参考。

    首先,在SQL Management Studio中创建一个数据库和相应的Table。

    例如:

    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 三个命名空间。代码如下:

    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 命名空间。代码如下:

    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三个简单的页面。

    Register页面代码:

    @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层。

  • 相关阅读:
    常见的 常见的 User_Agent
    scp 传送数据的几种方式
    最近面试的几个问题 (三) io 多路复用
    mac 磁盘分区 时间胶囊创建失败
    最近面试的几个问题 (二) request_url 去重之布隆去重
    最近面试的几个问题 (一) 进程和线程、协程的区别
    chromedriver与chrome最新版本对应表 转自-河岸上的酸菜鱼 简书地址-https://www.jianshu.com/u/bbea92f78aca
    Sql代码美化工具:Sql Pretty Printer for SSMS V3.6.1
    如何给非理科生讲明白什么是云计算、大数椐(下)
    如何给非理科生讲明白什么是云计算、大数椐(上)
  • 原文地址:https://www.cnblogs.com/Weimin496/p/7403810.html
Copyright © 2011-2022 走看看