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