MVC工作中的笔记~1(架构师是一步一步练成的)

如果你是一个对象MVC很痴迷但没有使用过的朋友,那你可以看这篇文章了。

1 Controller里的Create()方法, 一个用来显示VIEW,一个用来接入从VIEW提示过来的表单信息及便进行处理
  public ActionResult Create()         
        {
            product pro = new product()
            {};
            return View(new ProductFormViewModel(pro));
        }
       
        [AcceptVerbs(HttpVerbs.Post)]//筛选器,当有post事件时被触发
        public ActionResult Create(product pro) //这才是真正的create方法
        {
            if (ModelState.IsValid) //验证是否有效
            {
                try
                {
                    ProductRepository.Add(pro);
                    ProductRepository.Save();
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message);
                }

            }

            return View(new ProductFormViewModel(pro));

        }
2 对于View中的DropDownList的数据绑定
  //首先,2010-5-14这种绑定需要返回的数据源是个SelectList,所以,我们分三层说一下
  //View层代码:
  <%= Html.DropDownList("typeid", Model.Type )%>  
  // Controller层代码
   public class ProductFormViewModel
    {
        public product Product { get; private set; } //只能在类内部为它赋值,它对外是只读的属性
        public  SelectList  Type { get; private set; }
        public ProductFormViewModel(product _product)
        {
            Product = _product;
            ProductController pc=new ProductController(); //从Controller中得到它的一个实例
            //这名就是绑定了,首先是一个IEnumerabler的对象,后台是dropdownlist的值和文本
            Type = new SelectList(pc.ProductType(),"typeid","typename"); 
        }
    }
    public class ProductController : Controller
    {
        private Irepository ProductRepository;
        public ProductController()
            : this(new repository())
        {
        }
        public ProductController(Irepository res)
        {
            ProductRepository = res;
        }
        public IEnumerable ProductType() //反回一个IEnumerable的对象
        {
          
            IEnumerable<prodcutType> pt = ProductRepository.ProductType();
            return pt;
        }
//MODEL层代码:
namespace MvcApplicationTester.Models
{
    public class repository:Irepository
    {
        private DataClasses1DataContext con = new DataClasses1DataContext();
        
        public IQueryable<prodcutType> ProductType() //返回一个linq to sql的查询表
        {
            return con.prodcutType;
        }
        
    }
}

3 使用方法的属生,也称筛选器,来使方法在表单提交后执行。
 [AcceptVerbs(HttpVerbs.Post)]
4 页面是否被授权,如果为真,则执行方法 
 [Authorize] 
    如果授权和表单提交希望同时验证,可以这样作 
[AcceptVerbs(HttpVerbs.Post), Authorize]
5 Controller中的Edit()方法,需要先用id号取出数据,并返回视图,然后第二步才是修改数据,所以Edit方法也是由两个重裁的方法组成
    
    public ActionResult Edit(int id) //取出数据,反回视图的同时,传递回了pro这个对象
        {
            product pro = ProductRepository.GetProduct(id);
            return View(new ProductFormViewModel((pro)));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(int id,FormCollection collection) //根据ID号,对表单中的数据进行update
        {
            product pro = ProductRepository.GetProduct(id);
            try
            {
                UpdateModel(pro);  //注意,在使用updateModel为实体赋值时,要求表单元素名称与实体的属性名称要相同才行
                ProductRepository.Save();
                return RedirectToAction("Details", new {id = pro.productid});
            }
            catch (Exception err)
            {
              throw new Exception(err.Message);
            }
        }

6  [HandleError]筛选器,页面出现错误后,它会返回一个Error.aspx的视图,它可以在类前加,也可以在方法前加

7 Trigraphs运算符:如果 ?? 运算符的左操作数非 null,该运算符将返回左操作数,否则返回右操数

8 Linq实现inner join 的效果  
           student[] stu = {
                                new student{Name="zzl", Gander="male", Age=20, Score=99,Class=1}, 
                                new student{Name = "zql", Gander = "female", Age=19,Score = 100,Class=2}
                            };
            Classes[] cls = {
                                new Classes {Class = 1, ClassName = "一年级"},
                                new Classes {Class = 2, ClassName = "二年级"}

                            };
            var stuName = (from students in stu 
                            join class1 in cls on students.Class equals class1.Class 
                           select new 
                                      {
                                          _name=students.Name,  //别名为_name
                                          _gander=students.Gander,
                                          _score=students.Score,
                                          _classname=class1.ClassName
                                      });
            foreach (var name in stuName)
            {
                Response.Write(name._name + "   " + name._gander + "   " + name._score + "   " + name._classname + "<hr>");
            }

9 过滤器,也称为扩展方法,是对指定类型扩展添加的方法,在不改变原来类的结构,后续添加的方法
   public static class CatalogFilters 
     {     
         public static Category WithCategoryName(this IList<Category> list, string categoryName) 
          {
              return (from s in list
                    where s.Name.ToLower()==categoryName.ToLower()
                    select s).SingleOrDefault();
         }
       }
 

IList<Category> sample=数据源

sample.WithCategoryName(“zzl”); //直接就可以返回categoryName为zzl的实体对象一条

10 根据对象的构造方法的参数个数,来为类初始化值,这叫构造方法的重载
class OrderItem
    {
        public string ProductName{ get; set;}
        public int Count(get;set;)
        public OrderItem(string name)   //有点意思 ,当加载同名方法时,可以根据传递的参数个数,来加载指定的构造方法,
                                          这是重载,当然,如果希望实现对同一方法的不同功能,也可以在同名方法中,
                                          为固定的参数直接赋这初值
            : this(name,1) //当OrderItem方法只传递name参数时,它的第二个能数i被初始化为1,实事上,它只是个为类初始化的构造方法。
        {
        }
        public OrderItem(string name,int count)
        {
            this.ProductName = name;
            this.Count=count
        }  //通过实例,我们可以看到,当初始化类实例时OrderItem("梨"),这时,梨的Count就是1,
            当然,如果是OrderItem("梨",2),那么Count自然就是2了
}
posted @ 2011-08-03 16:23  张占岭  阅读(633)  评论(0编辑  收藏  举报