Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
894 views
in Technique[技术] by (71.8m points)

asp.net mvc - Using Html.BeginForm() with custom routes

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the Html.BeginRouteForm() method from the HtmlHelper class.

@Html.BeginRouteForm("MyCustomRoute", 
   new { controller = "MyController", action = "MyAction" })

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...