2

我有以下实体:ASP.NET MVC - 自定义模型绑定的ID字段

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; } 
} 

现在我添加类别视图中,我有一个文本框输入的SectionID如:

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

我想创建一个自定义模型联编程序以具有以下逻辑:

如果模型键以ID结尾并且有一个值(将值插入到文本框中),则设置父对象(本例中的Section )到Section.GetById(输入的值),否则将父对象设置为null。

我真的很感谢这里的帮助,因为这一直困扰着我。谢谢

回答

1

使用张贴戴夫解决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); 
    } 
} 

这工作得很好,但它不选择当窗体回正确的值,并使用下拉名单。我可以看到为什么,但迄今为止,我尝试修复它是徒劳的。如果你能提供帮助,我会再次感激。

+0

如果你还在研究这个,在if语句中你有'value.AttemptedValue =='“',然后在下一行你有'value.AttemptedValue!=”“',所以它看起来像它永远不会到达您的Section.GetById()代码。 – 2010-09-07 16:15:26

+0

再次为您的建议欢呼,但逻辑是正确的,即使它可以做一些整理,使其更具可读性。该问题的解决方案是创建一个处理SelectItem的Selected属性的自定义DropDownList。希望他们能够修复下一个版本的MVC中的错误。 – nfplee 2010-09-08 22:25:32

+0

我有一个自定义模型联编程序[在此处查看](http://stackoverflow.com/questions/19280598/best-way-to-do-partial-update-to-net-mvc-4-model/19297099#19297099 ),它尝试对属性进行排序,以便始终绑定标识字段。我让实际的视图模型类(在它的属性设置器中)触发它自己的存储库加载,而不是让自定义绑定器执行它。 (在重新阅读你的O.P.之后,我意识到这不是完全合适的,但是,也许会给别人一个想法) – bkwdesign 2013-10-14 20:03:06

2

我在this question上发布了一个模型联编程序,它使用IRepository来填充外键(如果它们存在)。你可以修改它以更好地适应你的目的。

+0

感谢您的链接。这对我迄今为止的工作确实有所帮助。如果你可以看看我的尝试解决方案,并帮助完成它,将非常感激:)。 – nfplee 2010-09-03 23:11:36