Url.RouteUrl

 

Url.RouteUrl 的多載方法有六種

 

要學習如何使用 Url.RouteUrl 的多載方法則要先去看 MapRoute 長什麼樣子,

才能決定 routeName、routeValues 的給定。

 

範例如下

RouteConfig.cs 的內容為

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace WebApplication1
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

 

Index.cshtml 的內容為

@{
    ViewBag.Title = "Home Page";

    RouteValueDictionary RouteValueDictionary = new RouteValueDictionary();

    RouteValueDictionary.Add("action", "Contact");

    RouteValueDictionary id = new RouteValueDictionary();

    id.Add("id", "5");
}

<table>
    <tr>
        <td>public virtual string RouteUrl(object routeValues);</td>
        <td>@Url.RouteUrl(new { Controller = "Home", Action = "About" })</td>
    </tr>
    <tr>
        <td>public virtual string RouteUrl(RouteValueDictionary routeValues);</td>
        <td>@Url.RouteUrl(RouteValueDictionary)</td>
    </tr>
    <tr>
        <td>public virtual string RouteUrl(string routeName);</td>
        <td>@Url.RouteUrl("Default")</td>
    </tr>
    <tr>
        <td>public virtual string RouteUrl(string routeName, object routeValues);</td>
        <td>@Url.RouteUrl("Default", new { id = 3 })</td>
    </tr>
    <tr>
        <td>public virtual string RouteUrl(string routeName, RouteValueDictionary routeValues);</td>
        <td>@Url.RouteUrl("Default", id)</td>
    </tr>
    <tr>
        <td>public virtual string RouteUrl(string routeName, object routeValues, string protocol);</td>
        <td>@Url.RouteUrl("Default", new { id = 3 }, "http")</td>
    </tr>
    <tr>
        <td>public virtual string RouteUrl(string routeName, RouteValueDictionary routeValues, string protocol, string hostName);</td>
        <td>@Url.RouteUrl("Default", id, "http", "apple.com.tw")</td>
    </tr>
</table>

@section styles{
    <style>
        table, td {
            padding: 3px;
            border: 3px black solid;
        }
    </style>
}

 

結果為

 

參考資料:

UrlHelper.RouteUrl Method