2011-10-26 58 views
2

模型可以说我有类似如下绑定路由参数

/{controller}/{action}/{id} 

一个途径是可以将ID属性绑定在我的模型

public ActionResult Update(Model model) 
{ 
    model.Details.Id <-- Should contain the value from the route... 
} 

在哪里我的模型类是以下?

public class Model 
{ 
    public Details Details {get;set;} 
} 

public class Details 
{ 
    public int Id {get;set;} 
} 

回答

2

您将要创建自己的自定义模型联编程序。

public class SomeModelBinder : IModelBinder { 

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { 
     ValueProviderResult value = bindingContext.ValueProvider.GetValue("id"); 

     SomeModel model = new SomeModel() { Details = new Details() }; 
     model.Details.Id = int.Parse(value.AttemptedValue); 

     //Or you can load the information from the database based on the Id, whatever you want. 

     return model; 
    } 

} 

要注册粘结剂您添加到您的Application_Start()

ModelBinders.Binders.Add(typeof(SomeModel), new SomeModelBinder()); 

你的控制器就长得一模一样,你有它上面。这是一个非常简单的例子,但是最简单的方法。我很乐意提供任何额外的帮助。