在URL中.NET MVC自定义类型 [英] .net mvc custom types in urls

查看:183
本文介绍了在URL中.NET MVC自定义类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建设使用默认的URL路由一个asp.net MVC应用程序
«/ {控制器} / {行动} / {ID}»

I'm building an asp.net mvc app that uses the default url route «/{controller}/{action}/{id}»

我的问题是,在这条路线的最后一个项目,该ID。
MVC框架自动转换无论在投放ID在行动中声明的参数的类型。

My problem is with the last item in this route, the id. The mvc framework automatically casts whatever in put in the id to the type of the parameter declared in the action.

例如:

网址:/ myController的/ myaction / 1

url: /mycontroller/myaction/1

公共类myController的:控制器
{

public class mycontroller: Controller {

    public ActionResult myaction(int id)
    {
      // it works id == 1
    }

}

但是,如果我在行动宣布自定义的参数类型的MVC框架无法对参数路线的最后部分映射。

But if I declare in the action a parameter of a custom type the mvc framework is unable to map the last part of the route to the parameter.

例如:

网址:/ myController的/ myaction / xpto

url: /mycontroller/myaction/xpto

公共类myController的:控制器
{

public class mycontroller: Controller {

    public ActionResult myaction(MyType id)
    {
      // it fails to cast "xpto" to my type
    }

}

凡应在框架挖掘教它怎么办呢?

Where should I tap in the framework to teach it how to do it?

推荐答案

从路由数据值绑定到操作参数是通过模型绑定处理。默认的模型粘合剂,勿庸置疑,DefaultModelBinder。如果这种类型不会在你的路线,你的MyType类型的值绑定,那么你有两种选择:

Binding of values from the route data to an action argument is handled by the model binder. The default model binder is, unsurprisingly, DefaultModelBinder. If this type will not bind the value in your route to your MyType type, then you have two choices:


  • 更改所传递的路线之日起,这样DefaultModelBinder可以将其转换为MyType的实例不加修饰,或

  • 编写自定义模型绑定,并设置它作为您的MyType类型的模型绑定。如果谷歌ASP.NET MVC和型号的粘合剂,你会发现这样的例子。

这篇关于在URL中.NET MVC自定义类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆