-->

convert string into (object) routeValues C#

2019-08-20 19:08发布

问题:

I am writing an extension function for UrlHelper. This function will accept three String parameters. First param is ACTIOn, second is CONTROLLER and third is some RANDOM STRING.

example: url.customeURL("Index", "Home", "view=someview");

After accepting all these parameters, Extension function will return a URL with action, controller and a query string something like;

/Home/Index?view=someview

Here is my function:

public static string CustomUrlAction(this UrlHelper helper, string action, string controller, string parameters)
        {
            return helper.Action(action, controller, new { parameters });
        }

The problem I am facing with my current implementation is, when I pass PARAMETERS to routeValues object it makes the URL like:

/home/index?parameters=view=someview

Whereas I want it to create an URL like:

/Home/Index?view=someview

So is there anyway I can achieve this? I know this can be easily done with Url.Action("Index", "Home", new {"view=someview"})

But I have to do it with an extension function.

回答1:

I don't know if there is a better, more supported way, but this seems to work so you can use it

public static string CustomUrlAction(this UrlHelper helper, string action, string controller, string parameters)
        {
            return String.Format("{0}?{1}",helper.Action(action, controller),parameters);
        }


标签: c# urlhelper