Asp.net mvc 3 将路由参数绑定到模型
假设我有一条如下的路线Asp.net mvc 3 将路由参数绑定到模型,asp.net-mvc-3,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 SomeModelBinder : IModelBinder { public o
/{controller}/{action}/{id}
是否可以将id绑定到模型中的属性
public ActionResult Update(Model model)
{
model.Details.Id <-- Should contain the value from the route...
}
您需要创建自己的自定义模型绑定器
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;
}
}
要注册活页夹,请将其添加到应用程序\u Start()
然后,您的控制器看起来与上面的控制器完全相同。这是一个非常简单的例子,但却是最简单的方法。我很乐意提供任何额外的帮助
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;
}
}
ModelBinders.Binders.Add(typeof(SomeModel), new SomeModelBinder());