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()=null,
    @Gender char()=null,
    @City nvarchar()=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 > )
        {
        return RedirectToAction("Index");
        }
        else
        {
        return View();
        }
        }
    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 > )
        {
        return RedirectToAction("Index");
        }
        else
        {
        return View();
        }
        }
    3. Controller中UpdaetModel 更新 Model,获得提交过来的数据 
      1.  [HttpPost]
        [ActionName("Create")]
        public ActionResult Create_Post()
        {
        Employee employee = new Employee();
        UpdateModel<Employee>(employee); int numSucc = ;
        if (ModelState.IsValid)
        {
        EmployeeService employeeService = new EmployeeService();
        numSucc = employeeService.AddEmployee(employee);
        } if (numSucc > )
        {
        return RedirectToAction("Index");
        }
        else
        {
        return View();
        }
        }
  17. Service  新增数据服务:
    1. public int AddEmployee(Employee employee)
      {
      int numSucc = ;
      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;
      }
  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>
      }
      }
  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; }
      }
  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);
      }
    4. Controller的Create方法中必需的字段,添加验证检查处理
    5.  if (string.IsNullOrEmpty(employee.Name))
      {
      ModelState.AddModelError("Name", "姓名为必需字段");
      }
  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);
      }
  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());
      }

最新文章

  1. linux下cetos7无线网络设置办法
  2. STM32之通用定时器
  3. iOS7模拟器安装
  4. Bmob开发指南【android端】
  5. 从inet_pton()看大小端字节序
  6. Codeforces Round #207 (Div. 1) A. Knight Tournament(STL)
  7. Linux 的 Crontab 命令运用(转)
  8. VirtualBox启动虚拟机报错0x80004005
  9. 再学C++之C++中的全部关键字
  10. asp.net中XmlDocument解析出现出错,处理特殊字符
  11. stdint.h 文件 int8_t uint8_t int16_t uint16_t
  12. HDU 5800 To My Girlfriend(单调DP)
  13. bzoj1555 KD之死 贪心+堆优化
  14. PHP session有效期session.gc_maxlifetime详解
  15. RocketMQ部分数据消费不了问题排查
  16. Ansible-----条件判断与错误处理
  17. 关于第一次在IDEA上使用lombok时注解完全不起作用
  18. 基于ubuntu搭建 Discuz 论坛
  19. 多种方法实现 python 线程池
  20. 软工作业No.1。Java实现WC.exe

热门文章

  1. 剑指Offer面试题:23.二叉树中和为某一值的路径
  2. iOS开发系列—Objective-C之Foundation框架
  3. [.net 面向对象程序设计深入](5)MVC 6 —— 构建跨平台.NET开发环境(Windows/Mac OS X/Linux)
  4. MySQL Dll语句
  5. 【干货】JS版汉字与拼音互转终极方案,附简单的JS拼音输入法
  6. Azure Blob Storage 基本用法 -- Azure Storage 之 Blob
  7. 如何创建一个RESTful WCF Service
  8. Oozie分布式任务的工作流——脚本篇
  9. c#属性中的get和set属性
  10. 动态给div中新增html