要将参数从问号(?)更改为斜杠(/)在MVC应用程序中创建自定义扩展方法。首先,创建一个名为"LinkExtensions.cs"(或任何你想要的名称)的新类文件,确保它与你的项目在同一命名空间中。
在这个文件中,创建一个名为"ActionLinkWithSlash"的静态方法,接收与原始ActionLink相同的参数,但将URL参数的分隔符从问号(?)更改为斜杠(/)。以下是示例代码:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.Routing;
namespace Your.Namespace
{
public static class LinkExtensions
{
public static IHtmlContent ActionLinkWithSlash(this IHtmlHelper htmlHelper,
string linkText,
string action,
object routeValues,
object htmlAttributes)
{
var urlHelper = new UrlHelper(htmlHelper.ViewContext);
var url = urlHelper.Action(action, routeValues);
if (url.Contains("?"))
{
url = url.Replace("?", "/");
}
var tagBuilder = new TagBuilder("a");
tagBuilder.InnerHtml.Append(linkText);
tagBuilder.Attributes["href"] = url;
if (htmlAttributes != null)
{
var properties = htmlAttributes.GetType().GetProperties();
foreach (var property in properties)
{
tagBuilder.Attributes[property.Name] = property.GetValue(htmlAttributes, null)?.ToString();
}
}
return tagBuilder;
}
}
}
在这个代码片段中,我们假设你已经为你的MVC应用程序引用了所有必要的命名空间,所以没有必要更多地解释那些部分。
一旦你使用这个静态方法创建你的URL,那么就可以将参数从问号(?)更改为斜杠(/)。在你的视图中使用它的示例代码:
@using Your.Namespace
@Html.ActionLinkWithSlash("My Link Text", "MyAction", new { id = 123 }, null)
这将生成类似于以下链接的HTML代码:
My Link Text