这东西弄了大半天,第3种方法总是绑定失败。。发现绑错类型了= = 顺手记下这些,并把关键部分用红色字标明
参考随笔:ASP.NET MVC: 使用自定义 ModelBinder 过滤敏感信息
实体:
public class Site
{
/// <summary>
/// 网站名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 网站地址
/// </summary>
public string Url { get; set; }
{
/// <summary>
/// 网站名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 网站地址
/// </summary>
public string Url { get; set; }
}
1、实现 IModelBinder 接口
public class SiteModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
HttpRequestBase request = controllerContext.HttpContext.Request;
if (string.Compare(request.HttpMethod, HttpVerbs.Post.ToString(), true) == 0 && request.Form.Count > 0)
{
Site site = IoC.Resolve<Site>();
site.Name = request.Form["Name"];
site.Url = request.Form["Url"];
return site;
}
return null;
}
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
HttpRequestBase request = controllerContext.HttpContext.Request;
if (string.Compare(request.HttpMethod, HttpVerbs.Post.ToString(), true) == 0 && request.Form.Count > 0)
{
Site site = IoC.Resolve<Site>();
site.Name = request.Form["Name"];
site.Url = request.Form["Url"];
return site;
}
return null;
}
}
2、配置
方法一:直接在参数上使用
public void Site([ModelBinder(typeof(SiteModelBinder))] Site site)
{
{
return View();
}
方法二:标记在 Model 上
/// </summary>
/// 网站信息
/// </summary>
[System.Web.Mvc.ModelBinder(typeof(SiteModelBinder))]
public class Site
{
/// <summary>
/// 网站名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 网站地址
/// </summary>
public string Url { get; set; }
/// <summary>
/// 网站名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 网站地址
/// </summary>
public string Url { get; set; }
}
方法三:在 Global.asax.cs 文件中处理:
绑定的类型是模型,参数是模型绑定器
protected void Application_Start()
{
ModelBinders.Binders[typeof(Site)] = new SiteModelBinder();