代码之家  ›  专栏  ›  技术社区  ›  nfplee

ASP.NETMVC-用于ID字段的自定义模型绑定器

  •  2
  • nfplee  · 技术社区  · 14 年前

    public class Category
    {
        public virtual int CategoryID { get; set; }
    
        [Required(ErrorMessage = "Section is required")]
        public virtual Section Section { get; set; }
    
        [Required(ErrorMessage = "Category Name is required")]
        public virtual string CategoryName { get; set; }
    }
    
    public class Section
    {
        public virtual int SectionID { get; set; }
        public virtual string SectionName { get; set; }
    }
    

    现在在add category视图中,我有一个文本框来输入SectionID,例如:

    <%= Html.TextBoxFor(m => m.Section.SectionID) %>
    

    我想创建一个自定义模型绑定器,使其具有以下逻辑:

    如果model键以ID结尾并且有一个值(一个值被插入到textbox中),那么将父对象(本例中的部分)设置为节.GetById(输入值)否则将父对象设置为null。

    我真的很感激这里的帮助,因为这让我困惑了一段时间。谢谢

    2 回复  |  直到 14 年前
        1
  •  2
  •   Community CDub    7 年前

    我把一个模型活页夹贴在墙上 this question

        2
  •  1
  •   nfplee    11 年前

    使用dave thieben发布的解决方案,我得出以下结论:

    public class CustomModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
    
            if (bindingContext.ModelType.Namespace.EndsWith("Models.Entities") && value != null && (Utilities.IsInteger(value.AttemptedValue) || value.AttemptedValue == ""))
            {
                if (value.AttemptedValue != "")
                    return Section.GetById(Convert.ToInt32(value.AttemptedValue));
                else
                    return null;
            }
            else
                return base.BindModel(controllerContext, bindingContext);
        }
    }
    

    这很好地工作,但是当表单返回并使用下拉列表时,它没有选择正确的值。我知道为什么,但到目前为止,我试图修复它都是徒劳的。如果你能帮忙的话,我将再次感谢你。

    推荐文章