2011-05-27 45 views
0

我有以下類別:綁定在MVC asp.net複雜的類

public class Movie 
{ 
string Name get; set; 
string Director get; set; 
IList<Tag> Tags get; set; 
} 

public class Tag 
{ 
    string TagName get; set; 
} 

在我的控制器中我結合這樣的動作:public ActionResult Create([ModelBinder(typeof(MovieBinder))]Movie mo)

上theMovieBinder我的字符串轉換爲List<tag>。當我調試作品。

在電影粘結劑我有以下代碼

if (propertyDescriptor.Name == "Tags") 
     { 
      var values = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name); 
      if (values != null) 
      { 
       var p = values.AttemptedValue.Replace(" ", ""); 
       var arrayValues = p.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); 
       var list = new List<Tag>(); 
       foreach (string item in arrayValues) 
       { 
        list.Add(new Tag() { TagName = item }); 
       } 
       value = list; 
      } 
     } 

但我得到的ModelState中出現以下錯誤: 異常= {「參數轉換,從類型‘System.String’輸入「模型.Tag'失敗,因爲沒有類型轉換器可以在這些類型之間進行轉換。「}

我創建了一個標籤聯編程序,但它不起作用,有什麼想法? 謝謝!

+0

什麼這個答案發生了:http://stackoverflow.com/questions/6102850/modelbinding- asp-net-mvc-list/6102916#6102916沒有爲你工作嗎? – 2011-05-27 15:59:44

+0

是的!謝謝!但現在我有這種情況....我在哪裏創建類標記 – elranu 2011-05-27 16:08:49

回答

1

你可以模型綁定我suggested here適應這種新情況下,你都推出了Tag類:

public class MovieModelBinder : DefaultModelBinder 
{ 
    protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) 
    { 
     if (propertyDescriptor.Name == "Tags") 
     { 
      var values = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name); 
      if (values != null) 
      { 
       return values.AttemptedValue.Split(',').Select(x => new Tag 
       { 
        TagName = x 
       }).ToList(); 
      } 
     } 
     return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder); 
    } 
} 
+0

我做到了!但我得到的錯誤。當我調試它的作品。即使我看到Movie對象並且已經正確填充了屬性。但是當我做ModelState.isValid時,我得到了錯誤。我將在問題中編輯我的代碼。 – elranu 2011-05-27 16:16:39

+0

@elranu,確實有一個問題。我已經更新了我的答案以解決問題。如果您重寫模型聯編程序中的'GetPropertyValue'方法而不是'SetProperty',它將起作用。 – 2011-05-27 16:28:55

+0

是的!謝謝!!你在哪裏對! – elranu 2011-05-27 17:06:43