2012-04-27 62 views
5

有沒有辦法在C之前強制綁定屬性A和B?ASP.NET MVC(4) - 以特定順序綁定屬性

System.ComponentModel.DataAnnotations.DisplayAttribute類中有Order屬性,但會影響綁定順序嗎?

我想要做到的,是

page.Path = page.Parent.Path + "/" + page.Slug 
在自定義

ModelBinder的

+0

我是否正確地說,「page.Parent.Path'和'page.Slug'被綁定到表單中,並且你希望'page.Path'在綁定發生後立即被設置爲它們內容的連接?即表單中不存在'page.Path'值? – Dangerous 2012-04-27 13:33:54

+0

@危險正確,'page.Path'不在窗體上。我從表單中獲得'page.Parent.Id'和'page.Slug'。 – 2012-04-28 07:23:15

+0

我想在'page.Parent'和'page.Slug'綁定後建立'page.Path'。 – 2012-04-28 07:32:25

回答

0

我最初會推薦Sams回答,因爲它根本不涉及任何綁定的Path屬性。你提到你可以使用Path屬性連接值,因爲這會導致延遲加載發生。我想,因此您正在使用您的域模型來向視圖顯示信息。因此,我建議使用視圖模型僅顯示視圖中所需的信息(然後使用Sams答案檢索路徑),然後使用工具將視圖模型映射到域模型(即AutoMapper)。但是,如果您繼續在視圖中使用現有模型,並且無法使用模型中的其他值,則可以將路徑屬性設置爲自定義模型聯編程序中由表單值提供程序提供的值發生其他綁定(假定不在路徑屬性上執行驗證)。

所以,讓我們假設你有以下幾種觀點:

@using (Html.BeginForm()) 
{ 
    <p>Parent Path: @Html.EditorFor(m => m.ParentPath)</p> 
    <p>Slug: @Html.EditorFor(m => m.Slug)</p> 
    <input type="submit" value="submit" /> 
} 

而下面的視圖模型(或視情況而定域模型):

公共類IndexViewModel { 公共字符串ParentPath {得到;組; } public string Slug {get;組; } public string Path {get;組; } }

然後,您可以指定下列模型綁定:

public class IndexViewModelBinder : DefaultModelBinder 
    { 
     protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) 
     { 
      //Note: Model binding of the other values will have already occurred when this method is called. 

      string parentPath = bindingContext.ValueProvider.GetValue("ParentPath").AttemptedValue; 
      string slug = bindingContext.ValueProvider.GetValue("Slug").AttemptedValue; 

      if (!string.IsNullOrEmpty(parentPath) && !string.IsNullOrEmpty(slug)) 
      { 
       IndexViewModel model = (IndexViewModel)bindingContext.Model; 
       model.Path = bindingContext.ValueProvider.GetValue("ParentPath").AttemptedValue + "/" + bindingContext.ValueProvider.GetValue("Slug").AttemptedValue; 
      } 
     } 
    } 

最後指定該模型綁定是通過使用視圖模型以下屬性可用於:

[ModelBinder(typeof(IndexViewModelBinder))] 
1

爲什麼不實行Page屬性爲:

public string Path{ 
    get { return string.Format("{0}/{1}", Parent.Path, Slug); } 
} 

+0

這會導致所有頁面的祖先逐個加載。例如。如果您顯示10個頁面(每個層次中的層次3),這可能會導致額外的20個查詢到數據庫。 – 2012-04-28 07:10:43