简体   繁体   中英

C# MVC routing in FormMethod.Get: How to use route from route table

I have a FormMethod.Get that takes two parameters from a mostly read only form. These two parameters are the only query parameters needed to display all the other values on the read only form so they are text boxes (most of the values are DisplayFor() or disabled). Normally I can navigate to my read only form by typing .../Home/Edit/S6/B043 . However, because this is a form submission it shows a URL like this .../Home/Edit?Location=S6&Facility=B043 . How do I get it to show my route of .../Home/Edit/S6/B043 when I submit the form to get the rest of the data? Or do I have to go back to my original plan of using javascript with window.location.href = . Thank you.

@using (@Html.BeginForm("Edit", "Home", routevalues, FormMethod.Get, new { id = "get-card" }))
{
  // code here
}

Is there any special reason why you want to display your URL different? Whenever you submit(GET) the form the URL will have all the values and parameters you are sending back to your controller, if you are worried because some one will access the site using a URL like .../Home/Edit/S6/B043 then you can add that custom URL to your RoutConfig file like this.

routes.MapRoute("mycustomUrl", "Edit/{param1}/{param2}",
           new { controller = "controllerName", action = "Edit", 
                 param1 = UrlParameter.Optional,
                 param2 =UrlParameter.Optional }); 

After that you can call your view with .../Home/Edit/S6/B043 and will work. If you want to have a friendly URL you can use POST that way you will not see all the parameters on the URL but everything depends on what you want to accomplish.

You could always hand write the form tags and use the UrlHelper to create the URL. It will then be created server side and show appropriately as you want it.

<form id="get-card" method="get" action="@Url.Action("Edit", "Home", routevalues)">
<!-- code here -->
</form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM