简体   繁体   English

将参数传递给URL ASP.NET MVC

[英]Passing Parameter to URL ASP.NET MVC

I was just wondering what the best practice is for passing a parameter into a URL that contains characters that you do not wish to pass to the URL. 我只是想知道将参数传递到包含您不希望传递给URL的字符的URL的最佳实践是什么。 For example, I pass the string /LM/W3SVC/7/ROOT into the URL but I want to pass it without the backslashes, thus like LMW3SVC7ROOT 例如,我将字符串/LM/W3SVC/7/ROOT传递到URL中,但我希望不带反斜杠地传递它,因此就像LMW3SVC7ROOT

The way I currently do this is by using .Replace() . 我目前的方式是使用.Replace() This is the full line of code that I currently use <a href="@Url.Action("Errors", new { id=item.Application.Replace("/", "").Replace(".", "")})"> @Html.DisplayFor(modelItem => item.Application) </a> which works fine but throws out a warning every now and again so I was just wondering if this is the correct way of implementing it. 这是我当前使用的完整代码行<a href="@Url.Action("Errors", new { id=item.Application.Replace("/", "").Replace(".", "")})"> @Html.DisplayFor(modelItem => item.Application) </a>可以正常工作,但会<a href="@Url.Action("Errors", new { id=item.Application.Replace("/", "").Replace(".", "")})"> @Html.DisplayFor(modelItem => item.Application) </a>发出警告,所以我只是想知道这是否是实现它的正确方法。

'Possible unintended reference comparison; to get a value comparison, cast the right hand side to type 'string'

Thanks in advance. 提前致谢。

The problem you're getting is from var queryString = RouteData.Values["id"]; 您遇到的问题来自var queryString = RouteData.Values["id"]; . If you look in Visual Studio and hover over var it will tell you the type of that particular var , which in this case is Object . 如果您在Visual Studio中查看并将鼠标悬停在var ,它将告诉您该特定var的类型,在这种情况下为Object

Try: 尝试:

var queryString = RouteData.Values["id"].ToString();

In this case, you're finding yourself having to replace certain characters in your string, which probably means server side, you might be having to do some extra logic to cope without having these characters on the received string. 在这种情况下,您发现自己不得不替换字符串中的某些字符,这可能意味着服务器端,您可能不得不做一些额外的逻辑来应对,而不必在接收到的字符串上包含这些字符。 In your View, just wrap the id in Url.Encode : 在您的视图中,只需将id包装在Url.Encode

id = Url.Encode(item.Application)

You will receive this server side with the string decoded, ie /LM/W3SVC/7/ROOT 您将收到带有解码字符串的服务器端,即/LM/W3SVC/7/ROOT

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

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