Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/asp.net-mvc-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 3 将路由参数绑定到模型_Asp.net Mvc 3 - Fatal编程技术网

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());