Thursday, 23 June 2016

URL routing the Querystring - mvc

No comments
Enum :-

  public enum Section
    {
        PersonalDetails =1,
        Goals=2

    }

RouteConfig.cs


 routes.MapRoute(
               name: "Personal Details",
               url: "{controller}/{tabName}",
               defaults: new { controller = "Details", action = "Details" },
               constraints: new { tabName = "PersonalDetails" }
           );

            routes.MapRoute(
               name: "Goals",
               url: "{controller}/{tabName}",
               defaults: new { controller = "Details", action = "Details" },
               constraints: new { tabName = "Goals" }
           );


Controller

  public async Task<ActionResult> Details(string tabName)
        {
             int  TabId = (int)Enum.Parse(typeof(Section), tabName);//Get Id from enum
             Section section = (Section)System.Enum.Parse(typeof(Section), tabName.ToString());//Get in enum

            return View();
         }

View

@Html.DropDownListFor(x => x.SectionName, Model.lstSection, "Select My Type", new { @class = "form-control", onchange = "document.location.href='/Investor/'+this.options[this.selectedIndex].value;''" })


//Check route name in view

@if (HttpContext.Current.Request.RequestContext.RouteData.Values != null)
        {
            if (@HttpContext.Current.Request.RequestContext.RouteData.Values.ContainsKey("tabName"))
            {

                var actionName = HttpContext.Current.Request.RequestContext.RouteData.Values["tabName"].ToString();
                if (actionName == Section.PersonalDetails .ToString())
                {
                    <div id="PersonalDetails">
                        <div class="field">
                            @Html.Raw(Model.Content.Content)
                        </div>
                    </div>
                    <div class="clearfix">&nbsp;</div>
                }
            }

        }