2012-06-28 71 views
1

我有一個包含的標籤列表的申請人型號:ASP.NET MVC3自定義模型綁定問題

public class Applicant 
{ 
    public virtual IList<Tag> Tags { get; protected set; } 
} 

當提交表單時,有一個包含逗號分隔的標籤列表的輸入域用戶有輸入。我有一個自定義的模型綁定到這個列表轉換爲一個集合:

public class TagListModelBinder : IModelBinder 
{ 
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     var incomingData = bindingContext.ValueProvider.GetValue("tags").AttemptedValue; 
     IList<Tag> tags = incomingData.Split(',').Select(data => new Tag { TagName = data.Trim() }).ToList(); 
     return tags; 
    } 
} 

然而,當我的模型填充並傳遞到上POST控制器動作,標籤屬性仍是一個空列表。任何想法爲什麼它沒有正確填充列表?

+0

http://prideparrot.com/blog/archive/2012/6/customizing_property_binding_through_attributes – VJAI

+0

@馬克我沒有看到一個理由更換整個模型粘合劑作爲你的鏈接可能會建議。 –

+0

請檢查我的答案 – VJAI

回答

2

的問題是你有Tags財產protected set訪問。如果您將其更改爲public,則下面的內容可以正常工作。

public class Applicant 
{ 
    public virtual IList<Tag> Tags { get; set; } 
} 
2

模型聯編程序僅綁定提交的值。它不綁定在視圖中呈現的值。

您需要創建一個自定義EditorTemplate來根據需要呈現標記。

1

MVC可以already bind to a List,我會建議使用內置的技術,已經做到了你所需要的。

我沒有注意到有關添加活頁夾的任何代碼,您是否將ModelBinder添加到活頁夾中?

protected void Application_Start() 
{ 
    ModelBinders.Binders.Add(typeof(IList<Tag>), new TagListModelBinder()); 
} 
+0

是的,我確實將它添加到活頁夾中,並被調用。它只是不會填充在action方法參數中。 – arknotts

+0

我看着你的鏈接綁定到列表。不幸的是,這在我的場景中不起作用,因爲我在客戶端使用的JavaScript將所有內容放入一個輸入字段。 – arknotts