MVC - show different view than default during load

Viewed 45

I have to make changes to a MVC application.

Scenario: MVC app with various Views etc. Default View is "Views\Home\Index.cshtml" as per route map.

Issue: I need to load a different View depending on a value retrieved from the db by the system on startup. On opening the application, the database table is read to determine what view to show. This done via a static method in _layout.cshtml like this:

@if (@CarnetsMVC.Classes.Utilities.GetView =="??")
{
do something
}

And in the Utilities class:

        public static string WhatView()
        {
            try
            {
                DataRow row = (new DALUsers()).GetView().Tables[0].Rows[0]["view"].ToString();

            }
            catch
            {
                return "";
            }
        }

        public static string GetView 
        {
            get
            {
                return WhatView();
            }
        }

Example During normal working hours all users will see "Views\Home\Index.cshtml" but during the night each shift must see a specific view for that shift based on the View selected by the admin. What View is chosen and why is determined by external factors, so basically the app checks the db to determine the default view each time it loads.

Problem The HomeController Index method is not accessed during the system load. It only gets hit when the home page is refreshed.

What I have tried I tried jquery in the _layout view - still went to Home/Index.cshtml I tried returning the view path in HomeController/Index - only works if the user selects the home icon (home/index action) I tried various routemaps. I tried to hide/show in jquery in _layout.

How do I open another view programatically when the user opens the app?

1 Answers

So after the flood of feedback......I ended up figuring it out myself.

My noob solution:

In my Index.cshtml:

<div id="divLoadLastn"></div>

Then a script:

<script>
    $(window).on('load', function () {
        if (somevalue == 'True') {
            var _url = '@(Url.Action("NormalAction","Home",null, Request.Url.Scheme))?_type=' + '@Model';
            $("#divLoadLastn").load(_url);
        }
        else {
            var _url = '@(Url.Action("AlternativeAction","Home",null, Request.Url.Scheme))';
            $("#divLoadLastn").load(_url);
        }
    });

I used jquery .load to dynamically load a view into a <div id="divLoadLastn"></div> after determining what to load.

Related