ASP.NET MVC Notes - 01

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

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

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

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

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

时间: 2024-12-28 19:26:57

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

ASP.NET MVC 基础(01)

[ASP.NET MVC ]系列文章大致会包含这样一些内容: 1.ASP.NET MVC 的一些高级知识点: 2.ASP.NET MVC 的一些最新技术: 3.ASP.NET MVC 网站安全方面的知识: 4.缓存.日志和网站优化方面的知识: 5.一些常见的第三方组件的使用(如轻量级ORM - Dapper,Ninject等) 6.完整的项目实例 - 个人独立博客系统(只用于学习,博客园非常好,个人觉得没必要去建设一个自己的独立博客): 7.一些建站方面的知识分享.

ASP.NET MVC EF 01 框架搭建

1.自动属性 (1)自动属性(Auto-Implemented Properties),C#自动属性可以避免原来我们手工的来声明一个私有成员变量以及和属性get,set的书写. public class Kencery  //声明一个Kencery的类 { public int ID{get;set;}  //主键ID public string Name{get;private set;}  //只读属性名字 public int Age{get;set;}   //年龄 } 2.隐式类型va

在ASP.NET MVC中使用Knockout实践01,绑定Json对象

本篇体验在ASP.NET MVC下使用Knockout,将使用EF Code First创建数据库.最后让Knockout绑定一个Json对象. 创建一个领域模型. namespace MvcApplication3.Models { public class Product { public int Id { get; set; } public string Name { get; set; } public string Category { get; set; } public deci

ASP.NET MVC 01 - ASP.NET概述

本篇目录: ASP.NET 概述 .NET Framework 与 ASP.NET ASP.NET MVC简介 ASP.NET的特色和优势 典型案例 ▁▃▅ ASP.NET概述 ▅▃▁ 目前开发B/S系统的主要技术有ASP.NET.JSP.PHP等.其中ASP.NET是基于.NET平台创建动态网页的一种服务器端技术,使用它可以创建动态可交互的Web页面. 在Microsoft的.NET战略中,ASP.NET是其中一项的技术,从图1中可以看出ASP.NET是.NET Framework的重要组成部

ASP.NET MVC中实现属性和属性值的组合,即笛卡尔乘积01, 在控制台实现

在电商产品模块中必经的一个环节是:当选择某一个产品类别,动态生成该类别下的所有属性和属性项,这些属性项有些是以DropDownList的形式存在,有些是以CheckBoxList的形式存在.接着,把CheckBoxList的选中项组合生成产品SKU项. 本系列将在ASP.NET MVC中实现以上功能.但本篇,先在控制台实现属性值的笛卡尔乘积. 关于属性的类: public class Prop { public int Id { get; set; } public string Name {

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

PS:MVC出来很久了,工作上一直没机会用.出于兴趣,工作之余我将展开对MVC的深入学习,通过博文来记录所学所得,并希望能得到各位园友的斧正. 本文目录 理解一般意义上的MVC模式 MVC模式(Model-View-Controller)是软件工程中的一种软件架构模式,把软件系统分为以下三个基本部分: 模型(Model):模型用于封装与应用程序的业务逻辑相关的数据以及对数据的处理方法.“模型”有对数据直接访问的权力,例如对数据库的访问.“模型”不依赖“视图”和“控制器”,也就是说,模型不关心它会

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

匆匆2014,转眼就到末尾了.在这一年,你还有哪事情些想做而没有做? 2014年在我身上发生了两件意义重大的事,一是正月初一宝宝出生,我升级成为了爸爸:二是加入了瞬聘网,成为了技术负责人. 2014我计划想做的事,比如带家人去一次旅行.看完家里那几本想看而没看的书.写完[ASP.NET MVC 大牛之路]系列博客.做一个教育类的网站等等,计划其实都还算合理,但终究还是80%的事没有完成,50%的事根本没有去做. 去年结束了[ASP.NET MVC 小牛之路]系列,本来计划在2014年接着写大牛之

asp.net mvc 页面传值的方法总结

转自:http://msprogrammer.serviciipeweb.ro/2012/01/15/usual-methods-to-transfer-data-from-page-to-page-in-asp-net-mvc/ Usual Methods to transfer data from Page To Page in ASP.NET MVC Preamble: In ASP.NET ( like in PHP and other Web frameworks) there are

ASP.NET MVC验证框架中关于属性标记的通用扩展方法

http://www.cnblogs.com/wlb/archive/2009/12/01/1614209.html 之前写过一篇文章<ASP.NET MVC中的验证>,唯一的遗憾就是在使用Data Annotation Validators方式验证的时候,如果数据库是Entityframework等自动生成的文件,就没有办法使用扩展属性标记进行标记.现在已经开始有了一些其它的Asp.net MVC 验证框架,使用上跟Data Annotation Validators差不太多,但是普遍有这样