将路由参数绑定到模型

时间:2011-10-26 23:57:07

标签: asp.net-mvc-3

假设我有类似以下的路线

/{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;}
}

1 个答案:

答案 0 :(得分: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());

然后您的控制器看起来与上面的完全一致。这是一个非常简单的例子,但是最简单的方法。我很乐意提供任何额外的帮助。

相关问题