asp.net mvc

asp.net mvc Model Binder

2017-12-14  本文已影响11人  落地成佛

1、按照如下顺序查找绑定到Model 上的值:

2 调用 Model Binding 方式

2.1 自动调用

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

2.2 手动调用

public ActionResult DisplayAddress() {
   IList<Address> addresses = new List<Address>();
   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 "<Not Specified>";
        else 
            return (string)result.AttemptedValue;
    }
}

8.2 注册

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

猜你喜欢

热点阅读