[HttpPost] public ActionResult Create(FormCollection formCollection) { //foreach (string key in formCollection.AllKeys) //{ // Response.Write(key + " ...
- inetmgr 進入IIS
- ViewBag和ViewData在run-time的時候檢查錯誤,View中的用法如下:
-
@*ViewBag傳遞的是動態對象*@ @foreach (string item in ViewBag.listData) { <li>@item</li> } ----------------------------------------- @*ViewData傳遞的是Object,所以要轉換類型*@ @foreach (string item in (List<string>)ViewData["Countries"]) { <li>@item</li> }
- web.config中連接字元串名稱需要和DbContext的類名稱一致:
-
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= ; " />
- Global.ashx 程式運行初始化配置:
-
//DBFirst從數據讀取數據,程式運行的時候EmployeeContext初始化為Null Database.SetInitializer<MVCBlog.Models.EmployeeContext>(null);
- View需要List數組對象,則強類型直接定義為IEnumerable; View中@using引用需要用到的類
-
@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>
- 業務邏輯層獲取數據
-
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; } } }
- Razor中構建DropList:
-
@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" }) - Procedure AddEmployee
-
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
- Controller搜集從View頁面Post過來的數據,有三種方法:
- FormCollection 中包含了所有表單數據的鍵值對集合,通過FromCollection[Key] 訪問到View Post 過來的 Data
-
[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
-
- 直接以參數的形式接收數據
-
[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
-
- Controller中UpdaetModel 更新 Model,獲得提交過來的數據
-
[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
-
- FormCollection 中包含了所有表單數據的鍵值對集合,通過FromCollection[Key] 訪問到View Post 過來的 Data
- Service 新增數據服務:
-
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
-
- 解決方案中的Nuget包管理器對解決方案中的Nuget包進行管理。
-
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);
- 進行數據的Delete動作必須在Post數據中執行
-
@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
-
- EF中欄位屬性的控制,如:[Required]、[Display(Name="")] 需在partial class中進行處理
-
[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
-
- Edit信息的時候不需要更新欄位的處理,如不需要更新Name。
- partial class 中 去掉 [Required]
- Edit方法中用 查出來的實體來存儲更新後的數據
-
[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 - Controller的Create方法中必需的欄位,添加驗證檢查處理
-
if (string.IsNullOrEmpty(employee.Name)) { ModelState.AddModelError("Name", "姓名為必需欄位"); }
View Code
- Lambda表達式,統計Department下Employee數量
-
[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
-
- Controller中Return View()中如果指定帶有尾碼的View,如index.cshtml,則需要傳遞完整路徑:
-
public ActionResult Index() { var employee = db.Employee.Include(e => e.Department); return View("~/Views/Employee/Index.cshtml",employee.ToList()); }
View Code
-