European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Understanding Produces And Consumes Attribute In MVC 6

clock July 31, 2018 11:41 by author Peter

Produces and Consumes Attributes are newly introduced in MVC 6 (ASP.NET Core) to control the content negotiation.

What is Content Negotiation?
The process of picking the correct output format is known as Content Negotiation. Generally, Frameworks will accept two types of input/output formats those are JSON and XML. Nowadays, every framework by default accepts and returns in JSON format because of its advantages. If the user wants to control this default behavior, he should send an Accept Header with an appropriate format in GET or POST request from a client such that Framework will make sure to use the given format.

If a user doesn’t provide any Accept-Header, then the framework will decide which format it should use based on its settings. Some of the most popular browsers such as Chrome and Firefox will by default add Accept Header as application/xml and that is the reason when we call the web API from the browser will display the output in XML format if we don’t explicitly set the output format as JSON. Below are the sample requests generated from Chrome and IE where can observe the Accept Headers for these two browsers.

Chrome
GET / HTTP/1.1
Host: localhost:8080
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

IE
GET / HTTP/1.1
Accept: text/html, application/xhtml+xml, */*


If you want to see the output in JSON format, it's preferred to use any tools like fiddler, browser dev tools etc.
To control this and let the user be given full control of how to receive and sent the data format, Produces and Consumes Attribute is introduced in new ASP.NET MVC Core.

Produces Attribute
This attribute helps the user to inform the framework to generate and send the output result always in given content type as follows.
[Produces("application/json")]  

The above line is saying to the framework to use JSON as output format. This attribute can be decorated at controller level as well as Action level. Action level will be taken as the first priority if it is declared at both controller level as well as Action level.

Consumes Attribute
An Attribute helps the user to inform the framework to accept the input always in given content type as follows.
[Consumes("application/json")]  

The above line is saying to the framework to use JSON as input format. This attribute can be decorated at controller level as well as Action level. Action level will be taken as the first priority if it is declared at both controller level as well as Action level.

If you want to control it globally, you can set this while configuring MVC in ConfigureServices method as follows.
Configure<MvcOptions>(options =>  
   Filters.Add(newProducesAttribute(“application/json”))  
); 



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Call A C# Function With jQuery AJAX In ASP.NET MVC?

clock July 27, 2018 11:42 by author Peter

jQuery AJAX method is a very powerful function for doing asynchronous operations from the Web pages. It helps to update parts of a Web page without reloading the whole page. This increases the Website's speed and reduces the load. It can be used with any Web technology like HTML, ASP.NET, ASP.NET MVC, PHP, Ruby or any other. With jQuery AJAX method, you can create high performance features in our Website. Let me show you how to use this method in  ASP.NET MVC page.

ASP.NET MVC Page
To understand the working of jQuery AJAX, I will create a login feature in ASP.NET MVC page. The page will have 2 input controls to enter the username and the password. There will also be a button to submit the two values for checking from the database.
When the username and password are correct, the secured information of the user is shown, else the “wrong username and password” is shown.
The main attraction here is that I will use jQuery AJAX method to check the username and the password. There will be no page reloading during checking.
To start learning jQuery AJAX method, I would suggest you check – jQuery AJAX. Also, look for the syntax and the key-value pairs that can be passed to this method.

The Controller Code
Start with creating a “Controller” in your ASP.NET MVC Application. Now, add a C# function “GetSecuredData” into the controller.
[HttpPost] 
public string GetSecuredData(string userName, string password) 

    string securedInfo = ""; 
    if ((userName == "admin") && (password == "admin")) 
        securedInfo = "Hello admin, your secured information is ......."; 
    else 
        securedInfo = "Wrong username or password, please retry."; 
    return securedInfo; 
}
 

The C# function given above will be called by jQuery AJAX method. As you can see, this function has 2 parameters, “username” and “password”. In these 2 parameters, it receives the username and the password values. It then checks them and shows the secured information, if they are the correct ones.

You can also change the code given above to include the database operation, where the username and the password are checked against the ones stored in the database.

The View code
Now, create a view for the Controller. This view will contain the two input controls for the username and password. There will be a button, which when clicked will call jQuery AJAX function.
<h3>Enter the Username and Password:</h3> 
(enter "admin" for both username and password) 
<input type="text" id="usernameInput" placeholder="Username" /> 
<input type="text" id="passwordInput" placeholder="Password" /> 
<button id="submit">Submit</button> 
<div id="dataDiv"></div> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> 
<script> 
    $(document).ready(function () { 
        $("#submit").click(function (e) { 
            if ($("#usernameInput").val() == "") 
                alert("Username cannot be empty"); 
            else if ($("#passwordInput").val() == "") 
                alert("Password cannot be empty"); 
            else { 
                $.ajax({ 
                    type: "POST", 
                    url: "/Home/GetSecuredData", 
                    contentType: "application/json; charset=utf-8", 
                    data: '{"userName":"' + $("#usernameInput").val() + '","password":"' + $("#passwordInput").val() + '"}', 
                    dataType: "html", 
                    success: function (result, status, xhr) { 
                        $("#dataDiv").html(result); 
                    }, 
                    error: function (xhr, status, error) { 
                        $("#dataDiv").html("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText) 
                    } 
                }); 
            } 
            return false; 
        }); 
    }); 
</script> 


The button click event will call jQuery AJAX event. We pass the “controller name/function name” to the URL field. The jQuery AJAX event will call the C# function which gets the username and password values in its parameters.

Finally in the success function we will show the returned value from the C# function.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How To Open PDF File In New Tab In MVC Using C# ?

clock July 24, 2018 07:46 by author Peter

In this post, we will learn about how to open PDF or other files in a new tab using C#. For this example, first we need to return a file from MVC Controller then open the file in a new tab from view. For this, I will set return type "FileResult" from MVC controller and return "File" with a byte Array of the file and its content type. Let's start coding.

Step 1
First, create a new project of MVC from File -> New -> Project.

Step 2
Select ASP.NET Web Application (.Net Framework) for creating an MVC application and set Name and Location of Project.

Step 3
After setting the name and location of the project, open another dialog. From this dialog select MVC project and click OK.

After creating a project create one controller method inside the home controller and name that "GetReport". and write the below code in this method.

Controller
public FileResult GetReport() 

    string ReportURL = "{Your File Path}"; 
    byte[] FileBytes = System.IO.File.ReadAllBytes(ReportURL); 
    return File(FileBytes, "application/pdf"); 
}


Above method returns FileBytes, and Content type is "application/pdf".

View
Create one function for an open PDF file in a new tab.
function GetClientReport() { 
    window.open('/{ControllerName}/GetReport, "_blank"); 
};


The above function will open a new tab in the browser and call controller GetReport() method and this method returns file ,and browser is displayed in an opened tab.



ASP.NET MVC 5 Hosting - HostForLIFE.eu :: Friendly Errors In MVC 5

clock July 20, 2018 08:51 by author Peter

In this article, I will be explaining 3 different ways to handle exceptions and display a friendly error page to the end user. Friendly Error Pages are the pages that you design to show the end user when any kind of not handled exception happens in your application and your expected result is not achieved. So, instead of presenting your end user with technical information regarding the exception, you show him a friend page. Also, presenting your end user with technical information is not a security best practice.

So, let's see the three ways.

Method 1: Custom Exception Filter
Custom Exception Filter

It is a filter that is called every time an exception occurs in the applied methods.

Why would I use a custom exception filter?


Because with a custom exception filter, you can handle in a generic way every kind of exception thrown by your actions and/or controllers. You may use custom exception filters to log your exceptions.

Steps to achieve this:
Step 1

Create a new class named CustomExceptionFilter.
public class CustomExceptionFilter : FilterAttribute, IExceptionFilter   
{   
    public void OnException( ExceptionContext filterContext )   
    {   
        filterContext.Result = new RedirectResult( "Home/About" );   
        filterContext.ExceptionHandled = true;   
    }   
}   

What this custom exception does is to redirect to your About action in your Home Controller. Do not forget to set the ExceptionHandled equal to true; otherwise it will not take effect.

Step 2
Apply your custom exception filter to your controller/action.
public class HomeController : Controller 

    [CustomExceptionFilter] 
    public ActionResult Index() 
    { 
        throw new Exception(); 
        return View(); 
    } 
 
    public ActionResult About() 
    { 
        ViewBag.Message = "Your application thrown an exception"; 
 
        return View(); 
    } 
 
    public ActionResult Contact() 
    { 
        ViewBag.Message = "Your contact page."; 
        throw new Exception(); 
        return View(); 
    } 


You can see that the exception filter is applied only to your Index Action so if you access your Contact action, you will be able to see the non-handled exception page.

Method 2: Web.Config configuration
Why would I handle an exception by web.config configuration?

It is easy to configure and useful when you do not need to log or work on the exception.

Steps to achieve this:

Step 1
Include this in your web.config inside the system.web tag.
<customErrors defaultRedirect="Error.cshtml" mode="On"></customErrors> 

Step 2
Update your Controller.
public class HomeController : Controller 

    [HandleError] 
    public ActionResult Index() 
    { 
        throw new Exception(); 
        return View(); 
    } 
 
    public ActionResult About() 
    { 
        ViewBag.Message = "Your application description page."; 
 
        return View(); 
    } 
 
    public ActionResult Contact() 
    { 
        ViewBag.Message = "Your contact page."; 
        throw new Exception();
        return View(); 
    } 


Observation - Like the custom exception filter, you may choose if you want to handle the exceptions at the Controller or Action level. Also, here, the handled exception is applied only to your Index action, you may see the non-handled error in the Contact View.

Method 3: Global.Asax Application_error
What is the Application_error?

It is to override the global exception handler of the application.

Why would I handle an exception by global.asax Application_error?
You do not need to set the places that you would like to handle the errors like before where you had to set the actions and controllers to be handled. Here, every exception will hit and be handled.

Steps to Achieve this:

Step 1
Update  your global.asax.
protected void Application_Error( object sender, EventArgs e ) 
  { 
      Exception exception = Server.GetLastError(); 
      Server.ClearError(); 
      Response.Redirect( "/Home/About" ); 
  } 


Like the custom exception handlers, it is very important to ClearError() in the Server. What is done here is the redirection of non-handled exceptions to the About action in the Home Controller. Congratulation, you just learned three good ways of handling exceptions in your application and presenting friendly error pages to your end users.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Use Log4net In ASP.NET MVC Application

clock July 17, 2018 08:30 by author Peter

You may have read several articles on how to use log4net; however,  this article explains how you can use it without having to initialize several times. Log4Net is a framework for implementing logging mechanisms. It is an open source framework. Log4net provides a simple mechanism for logging information to a variety of sources. Information is logged via one or more loggers. These loggers are provided at the below levels of logging:

  • Debug
  • Information
  • Warnings
  • Error
  • Fatal

Now let’s begin with implementation.

Add log4net Package

For this, you need to install log4net from NuGet Package Manager  to your ASP.NET MVC project as per the below screen.

Add Global.asax for loading log4net  configuration
Once installation is done, you need to add the below code in Application_Start() of  Global.asax
log4net.Config.XmlConfigurator.Configure(); 

Add log4net in config file
Now open web.config and enter the following details.
<configSections> 
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" /> 
</configSections> 

<log4net> 
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender"> 
<file value="C:\Temp\nSightsLog.log" /> 
<appendToFile value="true" /> 
<maximumFileSize value="500KB" /> 
<maxSizeRollBackups value="2" /> 
<layout type="log4net.Layout.PatternLayout"> 
  <conversionPattern value="%date %level %logger - %message%newline" /> 
</layout> 
</appender> 
<root> 
<level value="All" /> 
<appender-ref ref="RollingFile" /> 
</root> 
</log4net> 


Implementing in specific file for accessing throughout application
Add a class Log.cs in the Utilities folder.
Now, in the constructor of this class, instantiate logs for monitoring and debugger loggers.
private Log() 

 monitoringLogger = LogManager.GetLogger("MonitoringLogger"); 
 debugLogger = LogManager.GetLogger("DebugLogger"); 


Here, you need to create Debug(), Error(), Info(), Warn(), Fatal() methods which will call respective methods from Log4 net.

Below is a sample.

public class Log 

    private static readonly Log _instance = new Log(); 
    protected ILog monitoringLogger; 
    protected static ILog debugLogger; 

    private Log() 
    { 
        monitoringLogger = LogManager.GetLogger("MonitoringLogger"); 
        debugLogger = LogManager.GetLogger("DebugLogger"); 
    } 



    /// <summary> 
    /// Used to log Debug messages in an explicit Debug Logger 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    public static void Debug(string message) 
    { 
        debugLogger.Debug(message); 
    } 

    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    /// <param name="exception">The exception to log, including its stack trace </param> 
    public static void Debug(string message, System.Exception exception) 
    { 
        debugLogger.Debug(message, exception); 
    } 


    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    public static void Info(string message) 
    { 
        _instance.monitoringLogger.Info(message); 
    } 

    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    /// <param name="exception">The exception to log, including its stack trace </param> 
    public static void Info(string message, System.Exception exception) 
    { 
        _instance.monitoringLogger.Info(message, exception); 
    } 

    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    public static void Warn(string message) 
    { 
        _instance.monitoringLogger.Warn(message); 
    } 

    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    /// <param name="exception">The exception to log, including its stack trace </param> 
    public static void Warn(string message, System.Exception exception) 
    { 
        _instance.monitoringLogger.Warn(message, exception); 
    } 

    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    public static void Error(string message) 
    { 
        _instance.monitoringLogger.Error(message); 
    } 

    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    /// <param name="exception">The exception to log, including its stack trace </param> 
    public static void Error(string message, System.Exception exception) 
    { 
        _instance.monitoringLogger.Error(message, exception); 
    } 


    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    public static void Fatal(string message) 
    { 
        _instance.monitoringLogger.Fatal(message); 
    } 

    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="message">The object message to log</param> 
    /// <param name="exception">The exception to log, including its stack trace </param> 
    public static void Fatal(string message, System.Exception exception) 
    { 
        _instance.monitoringLogger.Fatal(message, exception); 
    } 

     


Now, you need to call the logger class that logs directly into your action method.

public ActionResult Login() 
  { 
      //This is for example , we need to remove this code later 
      Log.Info("Login-page started..."); 

      // Boolean msg = CheckSetupType(); 
      return View(); 
  }  

 



ASP.NET MVC 5 Hosting - HostForLIFE.eu :: List Of Users With Roles In ASP.NET MVC Identity

clock July 13, 2018 11:21 by author Peter

In this article, we will learn how to list all users with Associated Roles in ASP.NET MVC 5 using Identity. ASP.NET MVC 5 does not come with an inbuilt feature to list users with associated roles by default. However ASP.NET MVC have inbuilt UserManager, SignManager and RoleManager to assist this.

We need this feature in each of our applications as users are to be maintained along with their associated roles. We can apply a number of ideas to do this. In this article, we will learn a very simple way to list users with their associated RoleName as in the figure below.

Step 1
Create a View Model as Users-in-Role_ViewModel
public class Users_in_Role_ViewModel 
    { 
        public string UserId { get; set; } 
        public string Username { get; set; } 
        public string Email { get; set; } 
        public string Role { get; set; } 
    } 


Step 2
Add a new method called UsersWithRoles inside ManageUsersController and add the following codes.
public ActionResult UsersWithRoles() 
        { 
            var usersWithRoles = (from user in context.Users 
                                  select new 
                                  { 
                                      UserId = user.Id,                                       
                                      Username = user.UserName, 
                                      Email = user.Email, 
                                      RoleNames = (from userRole in user.Roles 
                                                   join role in context.Roles on userRole.RoleId  
                                                   equals role.Id 
                                                   select role.Name).ToList() 
                                  }).ToList().Select(p => new Users_in_Role_ViewModel() 
  
                                  { 
                                      UserId = p.UserId, 
                                      Username = p.Username, 
                                      Email = p.Email, 
                                      Role = string.Join(",", p.RoleNames) 
                                  }); 
  
  
            return View(usersWithRoles); 
        } 


Note - context.Users represents the table AspNetUsers which has navigation property roles which represent the AspNetUserInRoles table.

Step 3
Now, let’s add a View of UsersWithRoles method of ManageUsersController.
@model IEnumerable<MVC5Demo.UI.ViewModels.Users_in_Role_ViewModel> 
@{ 
    ViewBag.Title = "Users With Roles"; 
    Layout = "~/Views/Shared/_Layout.cshtml"; 

  
<div class="panel panel-primary"> 
    <div class="panel-heading"> 
        <h3 class="box-title"> 
            <b>Users with Roles</b> 
        </h3> 
    </div> 
    <!-- /.box-header --> 
    <div class="panel-body"> 
        <table class="table table-hover table-bordered table-condensed" id="UsersWithRoles"> 
            <thead> 
                <tr> 
                    <td><b>Username</b></td> 
                    <td><b>Email</b></td> 
                    <td><b>Roles</b></td> 
                </tr> 
            </thead> 
            @foreach (var user in Model) 
            { 
                <tr> 
                    <td>@user.Username</td> 
                    <td>@user.Email</td> 
                    <td>@user.Role</td> 
                     
                </tr> 
            } 
        </table> 
    </div> 
  
    <div class="panel-footer"> 
        <p class="box-title"><b>Total Users till @String.Format("{0 : dddd, MMMM d, yyyy}", DateTime.Now)  : </b><span class="label label-primary">@Model.Count()</span></p> 
    </div> 
</div> 
  
  
@section scripts{ 
    <script> 
        $(function () { 
            $('#UsersWithRoles').DataTable({ 
                "paging": true, 
                "lengthChange": true, 
                "searching": true, 
                "ordering": true, 
                "info": true, 
                "autoWidth": true 
            }); 
        }); 
    </script> 


Now, the above method and View will return the users to their roles.

n



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Project Modules In Treeview Using Angular And MVC

clock July 10, 2018 08:58 by author Peter

AngularJS is an MVC based framework. Google developed AngularJS. AngularJS is an open source project, which can be used freely, modified and shared by others.
Top features Of AngularJS

  • Two Way Data-Binding
    This means that any changes to the model update the view and any changes to the view updates the model.
  • Dependency Injection
    AngularJS has a built-in Dependency Injection, which makes application easier to develop, maintain and debug in addition to the test.
  • Testing
    Angular will test any of its code through both unit testing and end-to-end testing.
  • Model View Controller
    Split your application into MVC components. Maintaining these components and connecting them together means setting up Angular.
Prerequisites
  • Visual Studio 2017 Version 15.7.3
  • Microsoft .NET Framework Version 4.7
  • Microsoft SQL Server 2016
  • SQL Server Management Studio v17.7
In this project, the description is about the steps to create treeview structure of File and SubFile using AngularJS in MVC and This procedure can be implemented in case of Modules and related pages under each module in ERP type of project. So, here I show you a  project  which you can implement in a real-time scenario for better understanding of how many pages there are under respective Modules and the relation between Module and its corresponding pages.
Steps To Be Followed:
Step 1
Create a table named "Treeviewtbl".
Here I have a general script of Table creation with some dummy records inserted. You can find this SQL file inside the project folder named
"Treeviewtbl.sql"
Step 2
Then I have created an MVC application named "FileStructureAngular".
Step 3
Here I have added Entity Data Model named "SatyaModel.edmx" . Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add. A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.
Step 4
Inside HomeController I've added the following code.

Code Ref

 

    using System.Collections.Generic; 
    using System.Linq; 
    using System.Web; 
    using System.Web.Mvc; 
     
    namespace FileStructureAngular.Controllers 
    { 
        public class HomeController : Controller 
        { 
            // 
            // GET: /Home/ 
            public ActionResult Index() 
            { 
                return View(); 
            } 
     
            public JsonResult GetFileStructure() 
            { 
                List<Treeviewtbl> list = new List<Treeviewtbl>(); 
                using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities()) 
                { 
                    list = dc.Treeviewtbls.OrderBy(a => a.FileName).ToList(); 
                } 
     
                List<Treeviewtbl> treelist = new List<Treeviewtbl>(); 
                if (list.Count > 0) 
                { 
                    treelist = BuildTree(list); 
                } 
     
                return new JsonResult { Data = new { treeList = treelist }, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; 
            } 
      
            public void GetTreeview(List<Treeviewtbl> list, Treeviewtbl current, ref List<Treeviewtbl> returnList) 
            { 
                var childs = list.Where(a => a.ParentID == current.ID).ToList(); 
                current.Childrens = new List<Treeviewtbl>(); 
                current.Childrens.AddRange(childs); 
                foreach (var i in childs) 
                { 
                    GetTreeview(list, i, ref returnList); 
                } 
            } 
     
            public List<Treeviewtbl> BuildTree(List<Treeviewtbl> list) 
            { 
                List<Treeviewtbl> returnList = new List<Treeviewtbl>();   
                var topLevels = list.Where(a => a.ParentID == list.OrderBy(b => b.ParentID).FirstOrDefault().ParentID); 
                returnList.AddRange(topLevels); 
                foreach (var i in topLevels) 
                { 
                    GetTreeview(list, i, ref returnList); 
                } 
                return returnList; 
            } 
        } 
    } 

 

Code Description
Fetch data from the database and return it as a JSON result. 

    public JsonResult GetFileStructure()  
            {  
                List<Treeviewtbl> list = new List<Treeviewtbl>();  
                using (CrystalGranite2016Entities dc = new CrystalGranite2016Entities())  
                {  
                    list = dc.Treeviewtbls.OrderBy(a => a.FileName).ToList();  
                }  
      
                List<Treeviewtbl> treelist = new List<Treeviewtbl>();  
                if (list.Count > 0)  
                {  
                    treelist = BuildTree(list);  
                }  
      
                return new JsonResult { Data = new { treeList = treelist }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };  
            }  

I used a recursion method required for angularTreeview directive. Recursion method for recursively getting all child nodes and getting a child of the current item:
public void GetTreeview(List<Treeviewtbl> list, Treeviewtbl current, ref List<Treeviewtbl> returnList) 
        { 
            var childs = list.Where(a => a.ParentID == current.ID).ToList(); 
            current.Childrens = new List<Treeviewtbl>(); 
            current.Childrens.AddRange(childs); 
            foreach (var i in childs) 
            { 
                GetTreeview(list, i, ref returnList); 
            } 
        } 

To find top levels items:

    public List<Treeviewtbl> BuildTree(List<Treeviewtbl> list) 
            { 
                List<Treeviewtbl> returnList = new List<Treeviewtbl>(); 
                var topLevels = list.Where(a => a.ParentID == list.OrderBy(b => b.ParentID).FirstOrDefault().ParentID); 
                returnList.AddRange(topLevels); 
                foreach (var i in topLevels) 
                { 
                    GetTreeview(list, i, ref returnList); 
                } 
                return returnList; 
            } 

Step 5

Add a partial class of "Treeviewtbl" class for adding an additional field for holding child items. 
Code Ref

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
 
namespace FileStructureAngular 

    public partial class Treeviewtbl 
    { 
        public List<Treeviewtbl> Childrens { get; set; } 
    } 

Here is a field property "children" for identifying child nodes. So we need to add an additional field in our Model. So, I will add a partial class to add an additional field to hold child items. 

Step 6

Add required files into our project. In this article, I am going to use angularTreeview directive. This a very popular directive to render treeview from hierarchical data in AngularJS application.

  • angular.treeview.css
  • angular.treeview.js
  • image folder
The angular.treeview.css file is present in the Contents Folder. The angular.treeview.js file is present in Scripts Folder. I have added 3 png files for folder closed, folder opened, and files inside folders.

Here folders are the Modules and files are the pages under respective modules.

Step 7

I have added a Javascript file, where we will write AngularJS code for creating an Angular module and an Angular controller. 
In our application, I will add a Javascript file into the Scripts folder. Go to Solution Explorer > Right click on "Scripts" folder > Add > New Item > Select Javascript file under Scripts > Enter file name (here in my application it is "myApp.js") > and then click on Add button.

var app = angular.module('myApp', ['angularTreeview']); 
app.controller('myController', ['$scope', '$http', function ($scope, $http) { 
    $http.get('/home/GetFileStructure').then(function (response) { 
        $scope.List = response.data.treeList; 
    }) 
}]) 

Add a dependency to your application module.
var app = angular.module('myApp', ['angularTreeview']);   

Here I created a module named myApp and registered a controller named myController and then added GetFileStructure controller action method of HomeController for fetching data from the database and it returned as a JSON result.
$http.get('/home/GetFileStructure').then(function (response) {  
        $scope.List = response.data.treeList;  
    })  
Step 8
Add view for that (here index action) named "Index.cshtml".


    ViewBag.Title = "Satyaprakash - Website Modules In Treeview"; 

 
@*<h2>Website Modules In Treeview</h2>*@ 
 
<fieldset> 
    <legend style="font-family:Arial Black;color:blue">Website Modules In Treeview File Structure</legend> 
    <div ng-app="myApp" ng-controller="myController"> 
        <span style="font-family:Arial Black;color:forestgreen">Selected Node : <span style="font-family:Arial Black;color:red">{{mytree.currentNode.FileName}}</span> </span> 
        <br/> 
        <br/> 
        <div data-angular-treeview="true" 
             data-tree-id="mytree" 
             data-tree-model="List" 
             data-node-id="ID" 
             data-node-label="FileName" 
             data-node-children="Childrens"> 
        </div> 
    </div> 
 
    <link href="~/Content/angular.treeview.css" rel="stylesheet" /> 
    @section Scripts{ 
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script> 
        <script src="~/Scripts/angular.treeview.js"></script> 
        <script src="~/Scripts/myApp.js"></script> 
    } 
</fieldset> 

Here I have created a module name and registered a controller name under this module.

<div ng-app="myApp" ng-controller="myController">  

Copy the script and css into your project and add a script and link tag to your page.

<link href="~/Content/angular.treeview.css" rel="stylesheet" />  
  @section Scripts{  
      <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>  
      <script src="~/Scripts/angular.treeview.js"></script>  
      <script src="~/Scripts/myApp.js"></script>  
  }  

Attributes of angular treeview are below.

  • angular-treeview: the treeview directive.
  • tree-id : each tree's unique id.
  • tree-model : the tree model on $scope.
  • node-id : each node's id.
  • node-label : each node's label.
  • node-children: each node's children.
<div data-angular-treeview="true" 
    data-tree-id="mytree" 
    data-tree-model="List" 
    data-node-id="ID" 
    data-node-label="FileName" 
    data-node-children="Childrens"> 
</div> 

Then I mentioned a span tag for showing the text of selected folder and file name inside treeview.

<span style="font-family:Arial Black;color:forestgreen">Selected Node : <span style="font-family:Arial Black;color:red">{{mytree.currentNode.FileName}}</span> </span>  
TREE attribute

  • angular-treeview: the treeview directive
  • tree-id : each tree's unique id.
  • tree-model : the tree model on $scope.
  • node-id : each node's id
  • node-label : each node's label
  • node-children: each node's children



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in