Tuesday, 11 December 2012

Custom MVC routing based on URL stored in database


 Hi,
     here  i am explaining step-by-step dynamic routing (url-rewriting) in MVC3 Razor according to database.
i think this will helpful to you.  



Database
Create two tables in database and insert some records according to below showing....



 CREATE TABLE [dbo].[MvcRoutes](
    [routeID] [int] IDENTITY(1,1) primary key,
    [routeName] [varchar](50) ,
    [routeIsActive] [bit]
)



CREATE TABLE [dbo].[MvcRouteParams](
    [paramID] [int] IDENTITY(1,1) primary key,
    [routeID] [int] references MvcRoutes(routeID),
    [paramKey] [varchar](50) ,
    [paramValue] [varchar](255) ,
    [paramLogicalUrl] [nvarchar](max) )















Global.asax


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

            SmartSignEntities db = new SmartSignEntities(); // Entity Name
            List<MvcRoutes> dbRoutes = (from b in db.MvcRoutes
                                       where b.routeIsActive == true
                                       orderby b.routeName
                                       select b).ToList();

            foreach (MvcRoutes route in dbRoutes)
            {
                string _id;
                string _controller = "";
                string _action = "";
                string _logicalURL = "";
                foreach (MvcRouteParams param in route.MvcRouteParams)
                {
                    if (param.paramKey.ToLower() == "controller")
                        _controller = param.paramValue;
                    else if (param.paramKey.ToLower() == "id")
                        _id = param.paramValue;
                    else if (param.paramKey.ToLower() == "action")
                        _action = param.paramValue;
                    _logicalURL = param.paramLogicalUrl;
                }
                if (string.IsNullOrEmpty(_logicalURL))
                {
                    _logicalURL = "{" + _controller + "}" + "/{" + _action + "}";
                }

                routes.MapRoute(
                   route.routeName, // Route name
                   _logicalURL, // URL with parameters
                   new { controller = _controller, action = _action, id = UrlParameter.Optional } );

            }

            routes.MapRoute(
               "Default", // Route name
               "{controller}/{action}/{id}", // URL with parameters
               new { controller = "Home", action = "Index", id = UrlParameter.Optional } );
        }


HomeController


  public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View("Index");
        }

        public ActionResult About()
        {
            return View("About");
        }

        public ActionResult ContactUs()
        {
            return View("ContactUs");
        }

        public ActionResult productDetails()
        {
            return View("productDetails");
        }
    }


_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
</head>
<body>
    <table width="100%" cellpadding="0" cellspacing="0">
        <tr style="font-family: Arial; background-color: Silver; padding: 10px;">
            <td height="50px">
                <h1>
                    Smartsign Design
                </h1>
            </td>
            <td>
                <ul>
                    <li>@Html.ActionLink("ContactUs", "ContactUs", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                </ul>

            </td>
        </tr>
    </table>
    @RenderBody()
</body>
</html>



View (About.cshtml)

@{
    ViewBag.Title = "About";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>About</h2>
<br />
<b>
Home ->> About.....
</b>

 
 Url looks like according to database entry

and create other views "ContactUs", "productDetails", "Index" in home controller