ASP.NET MVC Notes - 01

来源:http://www.cnblogs.com/i-shanghai/archive/2016/09/16/5814635.html
-Advertisement-
Play Games

[HttpPost] public ActionResult Create(FormCollection formCollection) { //foreach (string key in formCollection.AllKeys) //{ // Response.Write(key + " ...


  1. inetmgr 進入IIS
  2. ViewBag和ViewData在run-time的時候檢查錯誤,View中的用法如下: 
  3.    @*ViewBag傳遞的是動態對象*@
        @foreach (string item in ViewBag.listData)
        {
            <li>@item</li>
        }
        -----------------------------------------
        @*ViewData傳遞的是Object,所以要轉換類型*@
        @foreach (string item in (List<string>)ViewData["Countries"])
        {
            <li>@item</li>
        }
  4. web.config中連接字元串名稱需要和DbContext的類名稱一致:
  5. public class EmployeeContext : DbContext
        {
            //定義對應到資料庫表的對象集合
            public DbSet<Employee> Employees { get; set; }
        }
    
        <add name="EmployeeContext"
             providerName="System.Data.SqlClient"
             connectionString="Data Source=.;Initial Catalog=MVCSample;User ID= ;Password= ; "  />
  6. Global.ashx 程式運行初始化配置:
  7. //DBFirst從數據讀取數據,程式運行的時候EmployeeContext初始化為Null
        Database.SetInitializer<MVCBlog.Models.EmployeeContext>(null);
  8. View需要List數組對象,則強類型直接定義為IEnumerable; View中@using引用需要用到的類 
  9. @model IEnumerable<MVCBlog.Models.Employee>
    @using MVCBlog.Models
    
    @{
        ViewBag.Title = "Index";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    <h2>Index</h2>
    
    @*Controller 傳遞過來的是List對象,所以強類型定義為List<MVCBlog.Models.Employee>*@
    <ul>
        @foreach (Employee employee in @Model)
        {
            <li> @Html.ActionLink(employee.Name, "Details", new { @id = @employee.EmployeeID })  </li>
        }
    </ul>
  10. 業務邏輯層獲取數據
  11. public IEnumerable<Employee> employees
            {
                get
                {
                    string connectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
    
                    List<Employee> employees = new List<Employee>();
    
                    using (SqlConnection con = new SqlConnection(connectionString))
                    {
    
                        SqlCommand cmd = new SqlCommand("sp_GetAllEmployee", con);
                        cmd.CommandType = CommandType.StoredProcedure;
                        con.Open();
                        SqlDataReader sdr = cmd.ExecuteReader();
                        while (sdr.Read())
                        {
                            Employee employee = new Employee();
                            employee.EmployeeID = Convert.ToInt32(sdr["EmployeeID"]);
                            employee.Name = sdr["Name"].ToString();
                            employee.City = sdr["City"].ToString();
                            employee.Gender = Convert.ToChar(sdr["Gender"]); 
    
                            employees.Add(employee);
                        }
                        return employees;
                    }
                }
            }
  12. Razor中構建DropList:
  13.   @Html.DropDownList("Gender", new List<SelectListItem> {
                          new SelectListItem { Text="",Value="M"},
                          new SelectListItem{ Text="",Value="F"}
                    }, "Select Gender", htmlAttributes: new { @class = "control-label col-md-2" })
    //或者是在Controller中構建SelectList後,Razor中Render
      ViewBag.DepartID = new SelectList(db.Department, "ID", "Name", employee.DepartID); 

      @Html.DropDownList("DepartID", null, "Select Department",htmlAttributes: new { @class = "form-control" })
  14. Procedure AddEmployee
  15. CREATE PROCEDURE sp_AddEmployee
         @Name nvarchar(50)=null,
         @Gender char(1)=null,
         @City nvarchar(50)=null,
         @DateOfBirth DateTime=null
    AS
    BEGIN
        -- SET NOCOUNT ON added to prevent extra result sets from
        -- interfering with SELECT statements.
        Insert Into Employee(Name,Gender,City,DateOfBirth)
        values(@Name,@Gender,@City,@DateOfBirth)
    END
    GO
  16. Controller搜集從View頁面Post過來的數據,有三種方法:
    1. FormCollection 中包含了所有表單數據的鍵值對集合,通過FromCollection[Key] 訪問到View Post 過來的 Data
      1.  [HttpPost]
                public ActionResult Create(FormCollection formCollection)
                {
                    //foreach (string key in formCollection.AllKeys)
                    //{
                    //    Response.Write(key + " "); 
                    //    Response.Write(formCollection[key] + "<br/>");
                    //}
        
                    Employee employee = new Employee();
                    employee.Name = formCollection["Name"];
                    employee.Gender = Convert.ToChar(formCollection["Gender"]);
                    employee.City = formCollection["City"];
                    employee.DateOfBirth = Convert.ToDateTime(formCollection["DateOfBirth"]);
        
                    EmployeeService employeeService = new EmployeeService();
                    int numSucc = employeeService.AddEmployee(employee);
        
                    if (numSucc > 0)
                    {
                        return RedirectToAction("Index");
                    }
                    else
                    {
                        return View();
                    } 
                }
        View Code
    2. 直接以參數的形式接收數據
      1.  [HttpPost]
                public ActionResult Create(string Name,char Gender,string City,string DateOfBirth)
                { 
                    Employee employee = new Employee();
                    employee.Name = Name;
                    employee.Gender = Gender;
                    employee.City = City;
                    employee.DateOfBirth = Convert.ToDateTime(DateOfBirth);
        
                    EmployeeService employeeService = new EmployeeService();
                    int numSucc = employeeService.AddEmployee(employee);
        
                    if (numSucc > 0)
                    {
                        return RedirectToAction("Index");
                    }
                    else
                    {
                        return View();
                    }
                }
        View Code
    3. Controller中UpdaetModel 更新 Model,獲得提交過來的數據 
      1.  [HttpPost]
                [ActionName("Create")]
                public ActionResult Create_Post()
                {
                    Employee employee = new Employee();
                    UpdateModel<Employee>(employee);
        
                    int numSucc = 0;
                    if (ModelState.IsValid)
                    {
                        EmployeeService employeeService = new EmployeeService();
                        numSucc = employeeService.AddEmployee(employee);
                    } 
        
                    if (numSucc > 0)
                    {
                        return RedirectToAction("Index");
                    }
                    else
                    {
                        return View();
                    }
                }
        View Code
  17. Service  新增數據服務:
    1. public int AddEmployee(Employee employee)
              {
                  int numSucc = 0;
                  using (SqlConnection conn = new SqlConnection(connectionString))
                  {
                      SqlCommand cmd = new SqlCommand("sp_AddEmployee", conn);
                      cmd.CommandType = CommandType.StoredProcedure;
                      SqlParameter[] paras = new SqlParameter[] {
                          new SqlParameter("Name",employee.Name),
                          new SqlParameter("Gender",employee.Gender),
                          new SqlParameter("City",employee.City),
                          new SqlParameter("DateOfBirth",employee.DateOfBirth)
                      };
                      cmd.Parameters.AddRange(paras);
      
                      conn.Open();
                      numSucc = cmd.ExecuteNonQuery();
                  }
      
                  return numSucc;
              }
      View Code
  18. 解決方案中的Nuget包管理器對解決方案中的Nuget包進行管理。
  19. Controller中模型綁定的兩種方法:
    1,Bind 制定需要進行模型綁定傳遞到Controller中的數據。

    public ActionResult Edit_Post([Bind(Include = "Gender , City,DateOfBirth")]Employee employee)

    2,在UpdateModel中,傳遞需要更新或者是不需要更新的參數

    UpdateModel<Employee>(employee, null, null, new string[] { "Name" });

    3,定義IEmployee介面,Employee繼承自IEmployee.

    UpdateModel<IEmployee>(employee);
  20. 進行數據的Delete動作必須在Post數據中執行
    1.   @foreach (var item in Model)
          {
              using (Html.BeginForm("Delete", "Employee", new { id = item.ID }))
              {
                  <tr>
                      <td>
                          @Html.DisplayFor(modelItem => item.Name)
                      </td>
                      <td>
                          @Html.DisplayFor(modelItem => item.Gender)
                      </td>
                      <td>
                          @Html.DisplayFor(modelItem => item.City)
                      </td>
                      <td>
                          @Html.DisplayFor(modelItem => item.DateOfBirth)
                      </td>
                      <td>
                          @Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
                          @Html.ActionLink("Details", "Details", new { id = item.ID }) | 
                          <input type="submit" value="Delete"  onclick="return confirm('確定刪除 @item.Name 嗎 ')" />
                      </td>
                  </tr>
              }
          }
      View Code
  21. EF中欄位屬性的控制,如:[Required]、[Display(Name="")]  需在partial class中進行處理
    1. [MetadataType(typeof(EmployeeMetaData))]
          public partial class Employee
          {
      
          }
          public class EmployeeMetaData
          {
              [Required]
              [Display(Name = "姓名")]
              public string Name { get; set; }
      
              [Required]
              [Display(Name = "性別")]
              public char Gender { get; set; }
      
              [Required]
              [Display(Name = "所在城市")]
              public string City { get; set; }
      
              [Required]
              [Display(Name = "生日")]
              public DateTime DateOfBirth { get; set; }
               
              [Required]
              [Display(Name = "部門")]
              public int DepartID { get; set; } 
          }
      View Code
  22. Edit信息的時候不需要更新欄位的處理,如不需要更新Name。
    1. partial class 中 去掉 [Required]
    2. Edit方法中用 查出來的實體來存儲更新後的數據
    3.  [HttpPost]
              [ValidateAntiForgeryToken]
              public ActionResult Edit([Bind(Include = "ID,Gender,City,DateOfBirth,DepartID")] Employee employee)
              {
                  Employee employeeFromDB = db.Employee.Find(employee.ID);
      
                  //須要用你查出來的實體來存儲更新後的數據,不更新Name欄位
                  employeeFromDB.City = employee.City;
                  employeeFromDB.Gender = employee.Gender;
                  employeeFromDB.DepartID = employee.DepartID;
                  employeeFromDB.DateOfBirth = employee.DateOfBirth;
      
                  if (ModelState.IsValid)
                  {
                      db.Entry(employeeFromDB).State = EntityState.Modified;
                      db.SaveChanges();
                      return RedirectToAction("Index");
                  }
                  ViewBag.DepartID = new SelectList(db.Department, "ID", "Name", employee.DepartID);
                  return View(employee);
              }
      View Code
    4. Controller的Create方法中必需的欄位,添加驗證檢查處理
    5.  if (string.IsNullOrEmpty(employee.Name))
                  {
                      ModelState.AddModelError("Name", "姓名為必需欄位");
                  }
      View Code
  23. Lambda表達式,統計Department下Employee數量
    1.  [HttpGet]
              public ActionResult EmployeeByDepartment()
              {
                  var departmentTotals = db.Employee.Include("Department")
                      .GroupBy(d => d.Department.Name)
                      .Select(y => new DepartmentTotals
                      {
                          Name = y.Key,
                          Total = y.Count()
                      }).ToList().OrderByDescending(y => y.Total);
      
                  return View(departmentTotals);
              }
      View Code
  24. Controller中Return View()中如果指定帶有尾碼的View,如index.cshtml,則需要傳遞完整路徑:
    1.  public ActionResult Index()
              {
                  var employee = db.Employee.Include(e => e.Department);
                  return View("~/Views/Employee/Index.cshtml",employee.ToList());
              }
      View Code

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1.安裝vsftpd 2.配置vsftpd.conf 3.添加ftp用戶 4.上傳許可權 5.設置vsftp 開機啟動 6.添加防火牆 ...
  • 每個人心裡都有一個建站夢,所以今天作為我第一篇文章,就給大家圓了這場夢。 今天我來詳細的一步一步帶領大家利用WordPress程式來建立自己的小站以及解決直接功能變數名稱訪問(本地安裝wordpress請閱讀《本地安裝WordPress》),首先建議大家在跟著我的步驟準備開始的時候先看看我的另一篇文章《Wo ...
  • I/O: 系統設定 預設輸入設備:標準輸入,STDIN,0 預設輸出設備:標準輸出,STDOUT,1 標準錯誤輸出:STDERR,2 屬於不同的數據流 標準輸入:鍵盤 標準輸出和錯誤輸出:顯示器 I/O重定向: 輸出重定向: > :覆蓋輸出 >> :追加輸出 2>:錯誤輸出 2>>:追加錯誤輸出 正 ...
  • ColorConsole htmlagilitypack.1.4.9.5 經測試效率比 CsQueryLaster 高 csvhelper Extend Devlib系列一套 itextsharp litedb log4net microsoft.bcl一套,.net4 await 用 MySql.... ...
  • 分別使用Controller和Filter方法完成登錄驗證,對比二者的優劣 ...
  • 分析ASP.NET MVC中隱藏處理的方法,使用記憶體隊列記錄日誌防止併發錯誤,Log4Net的使用方法及簡單應用 ...
  • 在 GUI 中執行非同步操作 序 目錄 一、在 GUI 程式中執行非同步操作 下麵通過窗體示例演示以下操作-點擊按鈕後:①將標簽內容改成:“Doing”,並將按鈕禁用(表示執行中);②線程掛起3秒(模擬耗時操作);③將標簽內容改為:“Complete”,並啟用按鈕(表示執行完成); 可是執行結果卻是: ...
  • 說說表達式樹 - Expression Trees 序 簡單說下表達式樹。 目錄 簡介 根據 Lambda 表達式創建表達式樹 通過 API 創建表達式樹 解析表達式樹 表達式樹永久性 編譯表達式樹 執行表達式樹 修改表達式樹 調試 簡介 表達式樹以樹形數據結構表示代碼,其中每一個節點都是一種表達式 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...