2012-02-07 29 views
10

我是新的使用自定義ModelBinders,我一直在環顧四周,找不到任何與此特定案例相關的帖子。MVC 3.0 ModelBinder bindingContext.ValueProvider.GetValue(key)在集合中綁定時返回null

我有這樣一個實體:

public class DynamicData 
    { 
     public IList<DynamicDataItem> DynamicDataItems{get;set;} 
    } 

在查看我綁定它像如下:

@Html.EditorFor(model => model.DynamicDataItems); 

我在班上DynamicDataItems特殊的信息,我想在一個檢索具體的方式,所以我創建了我自己的模型活頁夾。

public class DynamicDataItemBinder : IModelBinder 
    { 
     public object BindModel(ControllerContext controllerContext, 
      ModelBindingContext bindingContext) 
     { 
      var key = bindingContext.ModelName; 
      var valueProviderResult = bindingContext.ValueProvider 
       .GetValue(key); 

      if (valueProviderResult == null || 
       string.IsNullOrEmpty(valueProviderResult 
        .AttemptedValue)) 
      { 
       return null; 
      } 

      //Here retrieve my own Information 

      return DynamicDataItem; 
     } 
    } 

bindingContext.ModelName包含「DynamicDataItem [0]」。

如果我做了bindingContext.ValueProvider.ContainsPrefix(key),它會返回true,但是當我做GetValue(key)時,它會返回null。 如果我檢查ValueProvider包含什麼,我看到有幾個項目的密鑰從「DynamicDataItem [0]」開始。 我該如何檢索當前正在綁定的項目的所有字段的信息(「DynamicDataItem [0]」)? 我應該一一檢索它們嗎? 像這樣:

var result1= bindingContext.ValueProvider.GetValue("DynamicDataItem[0].Id"); 
var result2= bindingContext.ValueProvider.GetValue("DynamicDataItem[0].Name"); 

我會非常感謝你能不能給我任何與此指導。

+0

我建議您訪問[此鏈接] [1]。我認爲這對你的問題很有用。 [1]:http://stackoverflow.com/a/25902872/1817640 – Jahan 2014-10-01 23:47:18

回答

1

問題似乎是您正試圖將DynamicDataItem類型的對象綁定到輸入。由於DynamicDataItem不是字符串或其他原始類型,因此活頁夾找不到對輸入做什麼的直接方式,它將返回null。

假設類DynamicDataItem具有它自己的屬性,您想要做的是爲DynamicDataItem的每個屬性提供編輯。如果你所要做的只是從視圖中傳遞一個綁定了子對象集合的模型,那麼你甚至不需要自定義模型綁定器。我想你想的東西在你的觀點,讀起來更像是這個

<input type="text" name="DynamicDataItem[0].SomeTextField" /> 
<input type="text" name="DynamicDataItem[0].SomeOtherTextField" /> 

退房菲爾哈克和Scott Hanselman在的話題

HereHere

我希望幫助

1

我的same issue和你一樣,當我挖掘我發現你的網頁,我認爲這也可以幫助你:):

查看後this link給了我這個想法:基本上是試圖解析查詢字符串。你可以在controllercontext.httpcontext中找到它。

希望這可以幫助你

問候

0

我知道這是舊的文章,但我有同樣的問題,我的解決方案是使用的BindingContext。型號:

ValueProviderResult result = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name); 
if(result == null) 
    result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + "." + propertyDescriptor.Name); 
相關問題