2012-03-07 38 views
0

考慮建在下列方式HTML表單:現在ASP .NET MVC可以幫助我將ID轉換爲模型嗎?

 <select name="schoolType"> 
      @foreach (SchoolType schoolType in Model.SchoolTypes) 
      { 
       <option value="@schoolType.Id">@schoolType.Name</option> 
      } 
     </select> 

,SchoolType是一個模型類。它是在我的EDMX for Entity Framework中設計的。

在上述情況下,現在,我的操作方法是這樣的:

public ActionResult CreateSchool(int schoolType) 
    { 
     ... 
     SchoolType myType = container.SchoolTypeSet.FirstOrDefault(t => t.Id == schoolType); 
     ... 
    } 

是否可以編程某種幫助,使MVC會自動知道整數轉換成一個Model類有了這個ID,就像下面的動作方法簽名一樣?

public ActionResult CreateSchool(SchoolType schoolType) 
    { 
     ... 
    } 

回答

2

您可以使用一個模型綁定器來實現這一點:

public ActionResult CreateSchool([ModelBinder(typeof(SchoolTypeBinder))] SchoolType schoolType) 
{ 
    ... 
} 

如果你的模型綁定的樣子:

public class SchoolTypeBinder : IModelBinder 
{ 
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     SchoolType output = null; 

     int id; 
     ValueProviderResult parameter = bindingContext.ValueProvider.GetValue("id"); 
     if (parameter != null) 
     { 
      id = (int)parameter.ConvertTo(typeof(int)); 
      output = container.SchoolTypeSet.FirstOrDefault(t => t.Id == id); 
     } 
     return output; 
    } 
} 

你也可以用類型的粘合劑在全球範圍啓動相關聯:

protected void Application_Start() 
{ 
    ... 
    ModelBinders.Binders.Add(typeof(SchoolType), new SchoolTypeBinder()); 
} 

導致你請求的漂亮乾淨的動作:

public ActionResult CreateSchool(SchoolType schoolType) 
{ 
    ... 
} 
0

我通常將它包裝在一些名爲DataSource的抽象中,它公開當前值和當前ID。 只要主鍵通常都是相同類型的解決方案(int,Guid),您可以註冊數據源的模型聯編程序。 您可以使用某種幫助像下面將其輸出到您的視圖:

public static SelectList ToSelectList<T, T1>(this DataSource<T, T1> dataSource) 
    { 
     return dataSource == null 
      ? new SelectList(Enumerable.Empty<string>()) 
      : new SelectList(dataSource, "Key", "Value", dataSource.CurrentValue); 
    } 

而且在編輯器中的模板,你可以只使用 @ Html.DropDownListFor(型號=>模型,Model.ToSelectList())

相關問題