asp.net mvc Model Binder

2708 ワード

1.Modelにバインドされている値を次の順序で検索します。

  • Request.Form
  • RouteData.Values
  • Request.QueryString
  • Request.Files

  • 2 Model Binding方式を呼び出す


    2.1オートコール

    public ActionResult DisplayAddress(Address address) {
        return View(address);
    }
    

    2.2手動呼び出し

    public ActionResult DisplayAddress() {
       IList
    addresses = new List
    (); UpdateModel(addresses);// UpdateModel , TryUpdateModel(addresses);// TryUpdateModel , return View(address); }

    3、作用範囲(Includeで例を挙げる)


    3.1方法上

    public ActionResult DisplayAddress([Bind(Include = "Country")]Address address) {
        return View(address);
    }
    

    3.2アプリケーション

        //Model Address
        [Bind(Include = "Country")]
        public class Address {
              public string City { get; set; }
              public string Country { get; set; }
        }
    

    4、バインドには属性が含まれていません

    //
    public ActionResult DisplayAddress([Bind(Exclude = "Country")]Address address) {
        return View(address);
    }
    

    5、固定属性のバインド

    public ActionResult DisplayAddress([Bind(Include = "Country")]Address address) {
        return View(address);
    }
    

    7、接頭辞の追加

    //
    public ActionResult DisplayAddress([Bind(Prefix="HomeAddress")]Address address) {
        return View(address);
    }
    

    8、カスタムModel Binder


    8.1定義

    //  IModelBinder
    public class AddressBinder : IModelBinder {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
            Address model = (Address)bindingContext.Model ?? new Address();
            model.City = GetValue(bindingContext, "City");
            model.Country = GetValue(bindingContext, "Country");
            return model;
        }
    
        private string GetValue(ModelBindingContext context, string name) {
            name = (context.ModelName == "" ? "" : context.ModelName + ".") + name;
            ValueProviderResult result = context.ValueProvider.GetValue(name);
            if (result == null || result.AttemptedValue == "") 
                return "";
            else 
                return (string)result.AttemptedValue;
        }
    }
    

    8.2登録

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        ModelBinders.Binders.Add(typeof(Address), new AddressBinder());
    }