简体   繁体   English

C#MVC获取表单数据作为URL参数

[英]C# MVC Getting Form data as URL parameters

I have a controller that is accepting 3 values from a submitted form, this works fine. 我有一个控制器,它从提交的表单中接受3个值,效果很好。

What I need to do now, however is enable a generated link to post the same data to the controller. 但是,我现在需要做的是启用生成的链接以将相同的数据发布到控制器。

The controller looks like this: 控制器如下所示:

[HttpPost]
        public ActionResult Customer(string lastName, string postCode, string quoteRef)
        {

         // Using passed parameters here

        }

I am aware routing allows prettier URL's but in this case I need the form to be able to accept the three values either through the submitted form or by the following hyperlink format: 我知道路由允许使用更漂亮的URL,但是在这种情况下,我需要表单能够通过提交的表单或以下超链接格式接受这三个值:

path.to.url/Home/Customer?lastName={1}&postcode={2}&quoteRef={3}

I have looked into routing but I can't find anything that will allow me to achieve this outcome. 我已经研究过路由,但是找不到任何可以实现此结果的东西。

My routes are currently set up as the following: 我的路线目前设置如下:

routes.MapRoute(
                "Customer",
                "{controller}/{action}/{id}/{lastName}/{postCode}/{quoteRef}", 
                new {controller = "Home", action = "Customer", id = ""}
                );

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id =                           UrlParameter.Optional }
            );

Just set the form action method to use GET instead of POST to send the parameters as query string 只需将表单操作方法设置为使用GET而不是POST即可将参数作为查询字符串发送

@using (Html.BeginForm("Customer", "Controller", FormMethod.Get

Decorate action method with HttpGet HttpGet装饰动作方法

[HttpGet]
public ActionResult Customer(string lastName, string postCode, string quoteRef)
{
}

path.to.url/Home/Customer?lastName={1}&postcode={2}&quoteRef={3}

this would work only for [HttpGet] attribute, not [HttpPost] 这仅适用于[HttpGet]属性,不适用于[HttpPost]

So your method should look like: 因此,您的方法应如下所示:

[HttpGet]
public ActionResult Customer(string lastName, string postCode, string quoteRef)
{

// Using passed parameters here

}

And if you still want to use [HttpPost] , you should make a little diffrence between GET and POST method, like here - you cannot have these methods with identical parameters. 而且,如果仍然要使用[HttpPost] ,则应在GETPOST方法之间稍加区别,例如此处所示-您不能使这些方法具有相同的参数。

URL: path.to.url/Home/Customer?lastName={1}&postcode={2}&quoteRef={3}&method={4} 网址: path.to.url/Home/Customer?lastName={1}&postcode={2}&quoteRef={3}&method={4}

[HttpGet]
public ActionResult Customer(string lastName, string postCode, string quoteRef, string method)
    { .. }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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