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());
      }

ASP.NET MVC Notes - 01的更多相关文章

  1. ASP.NET MVC 5 01 - ASP.NET概述

    本篇目录: ASP.NET 概述 .NET Framework 与 ASP.NET ASP.NET MVC简介 ASP.NET的特色和优势 典型案例 ▁▃▅ ASP.NET概述 ▅▃▁ 目前开发B/S ...

  2. ASP.NET MVC 基础(01)

    [ASP.NET MVC ]系列文章大致会包含这样一些内容: 1.ASP.NET MVC 的一些高级知识点: 2.ASP.NET MVC 的一些最新技术: 3.ASP.NET MVC 网站安全方面的知 ...

  3. ASP.NET MVC:01理解MVC模式

    ASP.NET MVC是ASP.NET Web应用程序框架,以MVC模式为基础. MVC:Model View Controller 模型-视图-控制器Model(模型):负责对数据库的存取View( ...

  4. ASP.NET MVC 5 系列 学习笔记 目录 (持续更新...)

    前言: 记得当初培训的时候,学习的还是ASP.NET,现在回想一下,图片水印.统计人数.过滤器....HttpHandler是多么的经典! 不过后来接触到了MVC,便立马爱上了它.Model-View ...

  5. Asp.Net MVC 实用视频教程

    [北盟学习BaMn.Cn] Asp.Net MVC 第01课--创建第一个项目.avi [北盟学习BaMn.Cn] Asp.Net MVC 第02课--自己建一个controller view.avi ...

  6. [asp.net mvc 奇淫巧技] 01 - 封装上下文 - 在View中获取自定义的上下文

    我们在asp.net 开发中已经封装了最强大的HttpContext,我们可以在HttpContext中可以获取到几乎任何想获取的东西,也可以在HttpContext写入需要返回客户端的信息.但是这些 ...

  7. [ASP.NET MVC 小牛之路]01 - 理解MVC模式

    本人博客已转移至:http://www.exblr.com/liam  PS:MVC出来很久了,工作上一直没机会用.出于兴趣,工作之余我将展开对MVC的深入学习,通过博文来记录所学所得,并希望能得到各 ...

  8. [ASP.NET MVC 大牛之路]01 - 开篇

    匆匆2014,转眼就到末尾了.在这一年,你还有哪事情些想做而没有做? 2014年在我身上发生了两件意义重大的事,一是正月初一宝宝出生,我升级成为了爸爸:二是进入了一家创业公司,成为了技术负责人. 去年 ...

  9. 笨鸟先飞之ASP.NET MVC系列之过滤器(01过滤器简介)

    过滤器 什么是过滤器? 过滤器(Filter) 主要的作用大致可以理解为把我们的附加逻辑注入到MVC框架的请求处理. 在ASP.NET MVC的请求处理中一种有19个管道事件分别是 BeginRequ ...

随机推荐

  1. 深入浅出NodeJS——数据通信,NET模块运行机制

    互联网的运作,最根本的驱动就是信息的交互,NodeJS 在数据交互这一块做的很带感,异步编程让人很惬意,关于 NodeJS 的数据通信,最基础的两个模块是 NET 和 HTTP,前者是基于 TCP 的 ...

  2. SSRS(rdl报表)分页显示表头和对表头的冻结处理

    基础环境 最近在公司做西门子某系统的二次开发,需要用到SQLServer Reporting Services(SSRS).我们用的SQL版本是SQLServer 2008 R2:在设计报表时,表格用 ...

  3. MySQL 常用的UPDATE操作

    标签:UPDATE 概述 测试环境:mysql 5.6.21 步骤 创建测试表 CREATE TABLE `product` ( `proID` ) NOT NULL AUTO_INCREMENT C ...

  4. EF:打开Oracle连接时报错

    基础提供程序在 Open 上失败. The underlying provider failed on Open. 解决:安装最新的ODTwithODAC121024.

  5. C语言 · 查找整数

    问题描述 给出一个包含n个整数的数列,问整数a在数列中的第一次出现是第几个. 输入格式 第一行包含一个整数n. 第二行包含n个非负整数,为给定的数列,数列中的每个数都不大于10000. 第三行包含一个 ...

  6. xamarin uwp数字证书公钥私钥

    对于数字证书存储导入到电脑中,采用如下方式: /// <summary> /// 导入证书 /// </summary> /// <param name="ra ...

  7. iOS开发-闪退问题-解决之前上架的 App 在 iOS 9 会闪退问题

    最新更新:(2015.10.02) 开发环境: Delphi 10 Seattle OS X El Capitan v10.11 需使用下列 HotfixID: 30398, PAServer Hot ...

  8. iOS-C基础

    iOS开发系列--C语言之基础知识 概览 当前移动开发的趋势已经势不可挡,这个系列希望浅谈一下个人对IOS开发的一些见解,这个IOS系列计划从几个角度去说IOS开发: C语言 OC基础 IOS开发(i ...

  9. WPF入门教程系列十六——WPF中的数据绑定(二)

    三.绑定模式 通过上一文章中的示例,学习了简单的绑定方式.在这里的示例,要学习一下绑定的模式,和模式的使用效果. 首先,我们来做一个简单示例,这个示例是根据ListBox中的选中项,去改变TextBl ...

  10. JS函数无响应

    自己定义了一个函数,比如说叫 addClass(),当按钮单击的时候响应 在添加了一些第三方Open JS API后就没反应了 原因分析:在代码没变动的情况下,很有可能是自己定义的函数名和第三方的冲突 ...