使用自定义路线Html.BeginForm() [英] Using Html.BeginForm() with custom routes
问题描述
这是因为你一定会知道的默认路由:
routes.MapRoute(
默认,//路线名称
{控制器} / {行动} / {ID},// URL带参数
新{控制器=开始,行动=索引,ID = UrlParameter.Optional} //参数默认
);
比方说,我用BeginForm()方法是这样的:
@using(Html.BeginForm(MyAction,myController的新{ID = 4}))
这会使下面的表单标签:
<形式方法=邮报行动=/ myController的/ MyAction / 4>
现在,让我们说我做了一个自定义路线:
routes.MapRoute(
MyCustomRoute,//路线名称
myController的/ {ID} / {}行动,// URL带参数
新{控制器=myController的行动=索引,ID = UrlParameter.Optional} //参数默认
);
当我创建了一个表格,我想它看起来是这样的:
<形式方法=邮报行动=/ myController的/ 4 / MyAction>
不过,如果我在例子中使用BeginForm()如上,我会得到相匹配的默认路由,而不是一个网址。 有没有办法告诉BeginForm()使用个性化的路线,而不是默认的开创了动作的URL时?或不BeginForm()总是产生如下的缺省路由模式的URL <? / p>
的我使用asp.net MVC 3,如果它很重要。的
您可以使用 Html.BeginRouteForm()
方法从HtmlHelper类。
@ Html.BeginRouteForm(MyCustomRoute
新{控制器=myController的行动=MyAction})
This is as you surely know the default route:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Start", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
Let's say I use the BeginForm() method like this:
@using (Html.BeginForm("MyAction", "MyController", new { id = 4 }))
This will render the following form tag:
<form method="post" action="/MyController/MyAction/4">
Now, let's say I've made a custom route:
routes.MapRoute(
"MyCustomRoute", // Route name
"MyController/{id}/{action}", // URL with parameters
new { controller = "MyController", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
When I create a form I'd like it to look like this:
<form method="post" action="/MyController/4/MyAction">
However, if I use BeginForm() as in the example above, I will get a url that matches the default route instead. Is there a way to tell BeginForm() to use my custom route instead of the default one when creating the url for the action? Or does BeginForm() always produce urls that follows the default route pattern?
I'm using asp.net mvc 3 if it matters.
You can use the Html.BeginRouteForm()
method from the HtmlHelper class.
@Html.BeginRouteForm("MyCustomRoute",
new { controller = "MyController", action = "MyAction" })
这篇关于使用自定义路线Html.BeginForm()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!