欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C# MVC模型绑定和自定义绑定(详细介绍)

程序员文章站 2022-06-07 18:17:57
...
   //系统自带绑定
   //Bind特性有三个属性,Include="包含字段";Prefix="含有字符串的字段";Exclude="不包含的字段"
    public class UsersController : Controller
    {
        //可写在参数中
        public ActionResult usersBind([Bind(Include = "UserName,Pwd",Prefix ="P",Exclude ="Id")]User user)
        {
            User users = new Models.User();
            //可调用UpdateModel方法事项绑定 ,代码手动编写比较灵活
            UpdateModel<User>(users, new string[] { "Id", "UserName" });
            return View();
        }

    }
    //也可写在类上面
    [Bind(Include = "UserName,Pwd", Prefix = "P", Exclude = "Id")]
    public class User
    {
        public int Id { get; set; }
        public string UserName { get; set; }
        public string Pwd { get; set; }

    }
  //自定义绑定
  public class MvcApplication : System.Web.HttpApplication
    {
        //在Application_Start中声明绑定
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            ModelBinders.Binders.Add(typeof(User),new UserBinder());//通过ModelBinders调用绑定
        }
    }
 //继承接口IModelBinder实现BindModel()方法,来完成自定义绑定,可自定义改变规则
    public class UserBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var User = (User)bindingContext.Model ?? new User();
            User.Id = GetVaule<int>(bindingContext, "Id");
            string name = GetVaule<string>(bindingContext, "UserName");
            User.Pwd = GetVaule<string>(bindingContext, "Pwd");
            User.UserName = name + "ai";//如返回值结果多加个"ai"
            return User;
        }

        public T GetVaule<T>(ModelBindingContext bindingContext, string key)
        {
            ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(key);
            return (T)valueResult.ConvertTo(typeof(T));
        }
    }
   //调用执行Action前,会先执行绑定
     public ActionResult userBind(User user)
        {
            return View();
        }

C# MVC模型绑定和自定义绑定(详细介绍)

C# MVC模型绑定和自定义绑定(详细介绍)

C# MVC模型绑定和自定义绑定(详细介绍)

C# MVC模型绑定和自定义绑定(详细介绍)

C# MVC模型绑定和自定义绑定(详细介绍)