문제

I need to pass a query string to a redirect. I know you can do this like so:

return RedirectToAction("Index", new { param1 = "hello" });

will go to /Index?param1=hello.

But I need to pass a parameter which has a hyphen in the name. Let's call it "data-param". Since hyphens aren't allowed in C# names, I can't do this in the above way. I know in some places in MVC, underscores are used to handle this, but that doesn't work here either, the underscore is passed to the query string as-is.

So my question is, how do I redirect to /Index?data-param=hello?

도움이 되었습니까?

해결책

If you are trying to build a url, you can always slightly bypass the MVC routing and just pass the complete url in the old-fashioned way.

string dataParam="hello";
int otherParam=5;
return Redirect( String.Format("/Index?data-param={0}&data-param2={1}", dataParam, otherParam) );

If you are going outside of your own MVC application then you may not want RedirectToAction anyway unless you are redirecting to an action.

다른 팁

This works (I am using ASP.NET Core 3.1 and can't speak to earlier versions):

var params = new Dictionary<string, string>()
{
    { "data-param1", "hello" }
    { "data-param1", "2" }
};
return RedirectToAction("Index", params);

You can use Dictionary<string, object>() instead if you want, though you'll give up some control (e.g. false gets translated to "False" in the URL instead of "false"). And you should use nameof() for better maintainability:

var params = new Dictionary<string, object>()
{
    { "data-param1", "hello" }
    { "data-param2", 2 }
};
return RedirectToAction(nameof(Index), params);

Also note that this dictionary technique works with other methods too like RedirectToRoute().

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top