European ASP.NET MVC Hosting

BLOG about Latest ASP.NET MVC Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC Hosting - HostForLIFE.eu :: Display Mode Provider in MVC 5 Application

clock January 22, 2020 10:19 by author Peter

This article will solve a problem. Display modes in ASP.NET MVC 5 provide a way of separating page content from the way it is rendered on various devices, like web, mobile, iPhone, iPod and Windows Phones. All you need to do is to define a display mode for each device, or class of devices.

First you create a model and context class. We create an Employee class that has the following properties like.
    public class Employee 
    { 
        public Guid ID { get; set; } 
        [Display(Name="First Name")] 
        public string FirstName { get; set; } 
        [Display(Name = "Last Name")] 
        public string LastName { get; set; } 
        [Display(Name = "Department")] 
        public string Department { get; set; } 
        [Display(Name = "Salary")] 
        public double Salary { get; set; } 
        [Display(Name = "Address")] 
        public string Address { get; set; } 
    }


And second is the context class like this that inherits the DbContext class.
    public class DBConnectionContext:DbContext 
    {         
       public DBConnectionContext(): base("name=dbContext") 
       { 
             Database.SetInitializer(new DropCreateDatabaseIfModelChanges 
             <DBConnectionContext>()); 
       } 
            public DbSet<Employee> Employees { get; set; } 
    }


If you want to recreate data every time the model changes, add these lines of code.
    Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DbConnectionContext>());

You also have a web config file. We configure connectionStrings in the Web.Config file.
    <connectionStrings> 
    <add name="dbContext" connectionString="Data Source=localhost; Initial Catalog=CommonDataBase; Integrated Security=true"  
          providerName="System.Data.SqlClient" /> 
     </connectionStrings>


Then you create a controller class in a controller folder and edit the name as HomeController. Add a Scaffold to select a MVC 5 Controller with Views, using Entity Framework.

DisplayModes

DisplayModes give you another level of flexibility on top of the default capabilities we saw in the last section. DisplayModes can also be used along with the previous feature so we will simply build off of the site we just created. Let's say we wanted to show an alternate view for the Windows Phone 8, iPhone, iPod or Android.

Windows Phone 8 DisplayMode

Now that you have made the override files, you can use a DisplayMode to show them for the appropriate phones.

The best time to set this up is when the application starts. Here is our global.asax.cs, with the DisplayMode setup.
    DisplayModeProvider.Instance.Modes.Insert(1, new DefaultDisplayMode("WP") 
    { 
        ContextCondition = (ctx => ctx.GetOverriddenUserAgent() 
        .IndexOf("Windows Phone OS", StringComparison.OrdinalIgnoreCase) > 0)   
     }); 
      
    DisplayModeProvider.Instance.Modes.Insert(1, new DefaultDisplayMode("iPhone") 
    { 
        ContextCondition = (ctx => ctx.GetOverriddenUserAgent() 
        .IndexOf("iPhone", StringComparison.OrdinalIgnoreCase) > 0)   
    }); 
      
    DisplayModeProvider.Instance.Modes.Insert(1, new DefaultDisplayMode("Android") 
    { 
        ContextCondition = (ctx => ctx.GetOverriddenUserAgent() 
        .IndexOf("Android", StringComparison.OrdinalIgnoreCase) > 0)   
    }); 

The DisplayModeProvider Class
DisplayModeProvider holds a list of DefaultDisplayMode obejects, each representing display mode. And the provider holds the two display modes, default and mobile. The default display mode in an empty string and the second holds the mobile string.


We just create multiple View with [View].Android.cshtml, [View].iPhone.cshtml and so on for every device such as:

We create an index for iPhone and create a new employee in iPhone Index.iPhone.cshtml and Create.iPhone.cshtml.


We create an index for Windows Phone and create a new employee in the Windows Phone Index.WP.cshtml Create.WP.cshtml.


We create an index for Android and create a new employee in Windows Phone Index.Android.cshtml Create.Android.cshtml.



European ASP.NET Core Hosting :: Getting Started with Entity Framework Core

clock January 21, 2020 08:13 by author Scott

This walkthrough demonstrates the minimum required to create a database using Entity Framework Core in an ASP.NET Core application, and to develop basic CRUD screens. The walkthrough assumes that you have .Net Core SDK installed and that you have a suitable development environment/text editor. Visual Studio Code will be used in this example.

Creating an ASP.NET Core application link

If you have a version of Visual Studio that supports .Net Core (2015 or greater), you can use the project templates to create a new .Net Core Web application. Alternatively, you can use a command line tool to create and build the project. In this example, you will use the command line tool from within Visual Studio Code.

The first step is to create a folder for the application in a suitable location. Name the folder EFCoreWebDemo. Once created, open the folder in Visual Studio Code. Having done that, press Ctrl + ' to open a Terminal window.

Next, use the terminal to type these commands

dotnet new mvc 
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package --version 1.1.0-msbuild3-final Microsoft.EntityFrameworkCore.Tools
dotnet restore     
dotnet run
         

The commands above

- scaffolds a starter ASP.NET Core application that uses the MVC framework

- adds the Entity FrameworkCore and EF Core tooling packages from Nuget to the project

- restores all packages

- builds and runs the application

You should get confirmation that the application is running on port 5000:

If you navigate to http://localhost:5000 in your preferred browser, you should see the standard Microsoft MVC application running:

To continue with the next steps, stop the application by pressing Ctrl + C.

Open the EFCoreDemo folder in Visual Studio Code.

Modify the .csproj file to include the following section:

<ItemGroup>
    <DotNetCliToolReference
        Include="Microsoft.EntityFrameworkCore.Tools.DotNet"
        Version="1.0.0-msbuild3-final" />
</ItemGroup>

This step is only necessary if the .csproj file wasn't automatically modified to add the entry when the Tools package was installed. See https://github.com/aspnet/EntityFramework/issues/7358.

Once you have made this amendment, you can test to see if ef commands are available to you by navigating to the project folder in a terminal/command window and typing the following command:

dotnet ef -h

This should result in the initial help for the EF tools being displayed:

Creating the Model

Add a folder named Model to the application.

Add a new file named EFCoreWebDemoContext.cs to the Model folder and add the following code to it:

using Microsoft.EntityFrameworkCore;

namespace EFCoreWebDemo
{
    public class EFCoreWebDemoContext : DbContext
    {
        public DbSet<Book> Books { get; set; }
        public DbSet<Author> Authors { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {         optionsBuilder.UseSqlServer(@"Server=.\;Database=EFCoreWebDemo;Trusted_Connection=True;MultipleActiveResultSets=true");
        }
    }
}

Note: The model, particularly the DbContext class, is declared inside a namespace. If you don't place your context class in a namespace, you may come up against this long running open bug when adding your migration.

Next, add a new file named Author.cs and add the following code to it:

using System.Collections.Generic;

namespace EFCoreWebDemo
{
    public class Author
    {
        public int AuthorId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public ICollection<Book> Books { get; set; } = new List<Book>();
    }
}

Finally, add a new file named Book.cs and add the following code to it:

namespace EFCoreWebDemo
{
    public class Book
    {
        public int BookId { get; set; }
        public string Title { get; set; }
        public int AuthorId { get; set; }
        public Author Author { get; set; }
    }
}

This code defines classes for two entities - Book and Author that participate in a fully defined one-to-many relationship. The code also includes a class named EFCoreDemoContext that inherits from DbContext. This class has two DbSet properties that represent the tables in the database (which is yet to be created). The EFCoreWebDemoContext class also includes a method named OnConfiguring where the connection string for a SQL Server database is defined. You should change this to suit your environment and database provider.

Before moving on to the migration, type dotnet build to ensure that the application builds correctly.

Adding A Migration

Migrations are used to keep the database schema in sync with the model. There is no database at the moment, so the first migration will create it and add tables for the entities represented by the DbSet properties on the EFCoreDemoContext that you added.

Visual Studio Code doesn't provide any support (at the time of writing) for creating and executing migrations. Therefore they will be managed using the command prompt. Having opened one (if it's not still open from having created and built the application), navigate to the project folder and enter the following command:

dotnet ef  migrations add CreateDatabase

A new folder named Migrations is added to the project. It contains the code for the migration and a model snapshot.

Enter the following command to execute the migration:

dotnet ef database update

The database is created but all of the string fields are unlimited in size (nvarchar(MAX) in SQL Server).

Modifying The Database With Migrations

In the next section, you will modify the model to set limits to the size of selected string properties, and then use migrations to push those changes to the database schema.

Add the following to the using directives at the top of Author.cs and Book.cs:

using System.ComponentModel.DataAnnotations;

Modify the Book and Author entities so that they look like this:

public class Book
{
    public int BookId { get; set; }
    [StringLength(255)]
    public string Title { get; set; }
    public int AuthorId { get; set; }
    public Author Author { get; set; }
}

public class Author
{
    public int AuthorId { get; set; }
    [StringLength(50)]
    public string FirstName { get; set; }
    [StringLength(75)]
    public string LastName { get; set; }
    public ICollection<Book> Books { get; set; } = new List<Book>();
}

In the Terminal, type the following command:

dotnet ef migrations add LimitStrings

followed by

dotnet ef database update

This will scaffold a migration that will alter the size of the Book's Title field and the Author's FirstName and LastName fields. You should also get a warning that the scaffolded migration could lead to data loss. In this case, there is no data to be lost so the warning can be ignored.

Once the migration has been applied, the database schema will be altered. Here's how the modified Author table should look:

Working With Data

In the next section, you will create a web page for adding new authors to the database and for displaying them. Add a new file named AuthorController.cs to the Controllers folder. Add the following code to the newly created file:

using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace EFCoreWebDemo.Controllers
{
    public class AuthorController : Controller
    {
        public async Task<IActionResult> Index()
        {
            using (var context = new EFCoreWebDemoContext())
            {
                var model = await context.Authors.AsNoTracking().ToListAsync();
                return View(model);
            }           
        } 

        [HttpGet]
        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Create([Bind("FirstName, LastName")] Author author)
        {
            using (var context = new EFCoreWebDemoContext())
            {
                context.Add(author);
                await context.SaveChangesAsync();
                return RedirectToAction("Index");
            }
        }
    }
}

The code in the Index method retrieves all authors from the database and passes them to the View. The AsNoTracking method is used to prevent the context from unnecessarily tracking the data because it is intended for read-only use. The DbContext is instantiated in a using block to ensure that it is disposed properly.

The Create method that takes an Author as a parameter is responsible for adding the new author to the database. It uses the approach whereby data is added directly to the DbContext, allowing the context to infer the type of data to be added to the database.

Finally, add a new folder to the Views folder and name it Author. Add new file to the new folder called Index.cshtml. Add the following code to it:

@model IEnumerable<Author>
@{
    ViewBag.Title = "Authors";
}
<h1>@ViewBag.Title</h1>
<ul>
@foreach (var author in Model)
{
    <li>@author.FirstName @author.LastName</li>
}
</ul>

<div>@Html.ActionLink("New", "create")

Then add a new file named Create.cshtml to the Author folder with the following code:

@model Author
@{
    ViewBag.Title = "New Author";
}

<h1>@ViewBag.Title</h1>

@using(Html.BeginForm()){
  <div class="form-group">
    @Html.LabelFor(model => model.FirstName)
    @Html.TextBoxFor(model => model.FirstName, new { @class="form-control"})
  </div>
  <div class="form-group">
    @Html.LabelFor(model => model.LastName)
    @Html.TextBoxFor(model => model.LastName, new { @class="form-control"})
  </div>
  <button type="submit" class="btn btn-default">Submit</button>
}

Run the application by typing the following command:

dotnet run

Open a browser and navigate to http://localhost:5000/author/create. You should see a data entry form similar to this:

 

Enter an author's name and submit the form. You should get redirected to the index page where a list of any authors entered so far is displayed:

 

Adding Related Data

In the next section, you will add new books to the database which will be related to an existing author.

First, add a new file to the Controllers folder named BookController.cs. Add the following code to the new file:

using System.Threading.Tasks;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace EFCoreWebDemo.Controllers
{

    public class BookController : Controller
    {
        public async Task<IActionResult> Index()
        {
            using (var context = new EFCoreWebDemoContext())
            {
                var model = await context.Authors.Include(a => a.Books).AsNoTracking().ToListAsync();
                return View(model);
            }          
        } 

        [HttpGet]
        public async Task<IActionResult> Create()
        {
            using(var context = new EFCoreWebDemoContext())
            {
                var authors = await context.Authors.Select(a => new SelectListItem {
                    Value = a.AuthorId.ToString(),
                    Text = $"{a.FirstName} {a.LastName}"
                }).ToListAsync();
                ViewBag.Authors = authors;
            }
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Create([Bind("Title, AuthorId")] Book book)
        {
            using (var context = new EFCoreWebDemoContext())
            {
                context.Books.Add(book);
                await context.SaveChangesAsync();
                return RedirectToAction("Index");
            }
        }
    }
}

This time, the code in the Index method retrieves all authors and uses the Include method to eagerly load the related books from the database and passes them to the View. Again, the AsNoTracking method is used. The authors and their books only being used for display.

In the first Create method, each of the authors are retrieved from the database and projected into a new form - a SelectListItem. Non-entity types are not tracked by the context which is why the AsNoTracking method is not used in this case, despite the fact that the data is for read-only use.

The second Create method features an example of the entity being added to its DBSet, rather than the DbContext as was the case for the author.

Next, add a new folder to the Views folder named Book. Add a new file to the book folder named Index.cshtml and copy the following code into it:

@model IEnumerable<Author>
@{
                ViewBag.Title = “Authors and their books”;
}
<h1>@ViewBag.Title</h1>
@if(Model.Any()){
    <ul>
    @foreach(var author in Model){
        <li>@author.FirstName @author.LastName
            <ul>
            @foreach(var book in author.Books){
                <li>@book.Title</li>
            }
            </ul>
        </li>
    }
    </ul>
}
<div>@Html.ActionLink("New", "create")

Finally, add another file to the Views/Book folder named Create.cshtml and add the following code to it:

@model Book
@{
    ViewBag.Title = "New Book";
}

<h1>@ViewBag.Title</h1>

@using(Html.BeginForm()){
  <div class="form-group"
    @Html.LabelFor(model => model.AuthorId)
    @Html.DropDownListFor(model => model.AuthorId, (IEnumerable<SelectListItem>)ViewBag.Authors, string.Empty, new { @class="form-control"})
  </div>
  <div class="form-group">
    @Html.LabelFor(model => model.Title)
    @Html.TextBoxFor(model => model.Title, new { @class="form-control"})
  </div>
  <button type="submit" class="btn btn-default">Submit</button>
}

Execute the dotnet run command to build and run the application. You might need to press Ctrl + C to stop the application first. Once it is running again, navigate to http://localhost:5000/book/create where you should see a data entry screen like this:

The AuthorId dropdown should be populated with the the authors that you have so far entered into the application. Select one and enter a book title and hit the submit button. You should then be redirected to the Index view which will display a list of all authors and their books.



ASP.NET MVC Hosting - HostForLIFE.eu :: Prepare a Custom JSON Format in MVC or Remove JSON Key

clock January 9, 2020 11:15 by author Peter

This post explains how to remove a JSON key in JSON result in MVC or C#

We can create our own converter class:
    public class JsonKeysConverter : JsonConverter 
    { 
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 
        { 
            Module o = (Module)value; 
            JObject newObject = new JObject(new JProperty(o.Name, o.Permission)); 
            newObject.WriteTo(writer); 
        } 
     
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) 
        { 
            throw new NotImplementedException("The type will skip the converter."); 
        } 
     
        public override bool CanRead 
        { 
            get { return false; } 
        } 
     
        public override bool CanConvert(Type objectType) 
        { 
            return true; 
        } 
    } 
     
    [JsonConverter(typeof(JsonKeysConverter))] 
    public class Module 
    { 
        public string Name { get; set; } 
        public string[] Permission { get; set; } 
    } 
     
    public class Role 
    { 
        public class Roles 
        { 
            public Dictionary<string, List<string>> Modules {get; set;} 
        } 
    } 
     
    public static string json() 
    { 
            var oRoles = new Roles(); 
            oRoles.modules = new Module[] { 
                new Module(){ 
                    Name="Page-Profile", 
                    Permission=new string[]{ "Edit","View","Delete"} 
                }, 
                new Module(){ 
                    Name="User", 
                    Permission=new string[]{ "Edit","View","Delete","Update"} 
                } 
            }; 
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(oRoles); 
         
                     
            Dictionary<string, List<string>> modules = new Dictionary<string, List<string>>(); 
            modules.Add("Page-Profile", new List<string>() { "Edit", "View", "Delete"}); 
            modules.Add("User", new List<string>() { "Edit", "View", "Delete", "Update"}); 
             
            return JsonConvert.SerializeObject(modules);  


Output
{"Page-Profile":["Edit","View","Delete"],"User":["Edit","View","Delete","Update"]}  



ASP.NET MVC 6 Hosting United Kingdom - HostForLIFE.eu :: Compressing an ASP.NET MVC Response Manually

clock December 19, 2019 04:21 by author Peter

This post is regarding compression your http result while not using IIS Dynamic Compression. And this is code to compress ASP.NET MVC 6 Response Manually:

using System;
using System.IO.Compression;
using System.Web;
namespace WebCompressionSample
{
    public static class ResponseCompressor
    {
        public static void Compress(HttpContext context)
        {
           {
               return;
            }
            string acceptEncoding = context.Request.Headers["Accept-Encoding"];
            if (string.IsNullOrEmpty(acceptEncoding))
            {
                return;
            }
            if (acceptEncoding.IndexOf("gzip",
                StringComparison.OrdinalIgnoreCase) > -1)
            {
                       context.Response.Filter = new GZipStream(
                       context.Response.Filter, CompressionMode.Compress);
                       context.Response.AppendHeader("Content-Encoding", "gzip");

            }
            else if (acceptEncoding.IndexOf("deflate",
                StringComparison.OrdinalIgnoreCase) > -1)
            {
                    context.Response.Filter = new DeflateStream(
                    context.Response.Filter, CompressionMode.Compress);
                   context.Response.AppendHeader("Content-Encoding", "deflate");
            }
        }
    }
}

Well, this shows a way to do the compression itself. Looking on however you are doing ASP.NET MVC, you most likely can call it otherwise.In my case, I referred to as it manually from an ASP.NET Webforms PageMethod (more on why below), however if you're using ASP.NET MVC for instance, you most likely wish to wrap it in an ActionFilter and apply that to the action you wish to compress its output. Let me apprehend within the comments or on twitter if you've got a problem implementing it in a particular situation.

IIS 7+ has built in dynamic compression support (compressing output of server-side scripts like ASP.NET, PHP, etc.). It’s not by default as a result of compression dynamic content means that running the compression for each request (because it doesn’t know what the server-side script can generate for each request, the purpose of using server-side programming is generating dynamic content).

Static compression on the opposite side (caching static files like styles and scripts) is on by default as a result of once the static resource is compressed, the compressed version is cached and served for each future request of an equivalent file (unless the file changes of course). I’d say if your server side scripts expect to come large text-based content (say, large data, even when paging, etc. like large reports or whatever), always turn dynamic compression on, a minimum of for the pages that expect to come massive data sets of text.

In several cases though the majority of huge files will be scripts (and probably images) will be the larger components though, which are usually taken care of (for scripts for example) by IIS static compression or ASP.NET Bundling.



ASP.NET MVC Hosting - HostForLIFE.eu :: How to Use Google Calendar API?

clock December 6, 2019 11:27 by author Peter

In this article I will show you how to use Google Calendar in ASP.NET MVC. Google APIs use the OAuth 2.0 protocol for authentication and authorization. Google supports common OAuth 2.0 scenarios such as those for web server, installed, and client-side applications.It's more easily to log in your application via OAuth and OpenID provider in  ASP.NET MVC 4 now. Microsoft has few build-in client for Microsoft, Twitter, Facebook, Google. The Google client is based on OpenID and not OAuth. That's mean you can not access Google Data API.

In order to access Google Data API for web application. You need to register a Client ID to get Client ID an Client Secret for setting in your application.

You need to assign redirect URIs for grap OAuth access token callback also. Here we setup Rirect URIs as http://localhost:57271/Account/ExternalLoginCallback.

Google Client Library for .NET

The Google APIs Client Library for .NET is generic .NET runtime client for Google Services. The library supports OAuth2.0 authentication, and is able to generate strongly typed client libraries for Discovery-based services. Google Client library is a higher level library for using Google Data API. You can download beta version from Nuget in visual studio. It's more difficult to handle Google Client Library for .NET with few documents and sample now. Here, just using Google.Apis.Calendar.v3.Data namespace to our strong type class for data binding in deserialize object from API response.

    private Event GoogleEventHandle(string token, string method, string requestURL, string requestBody = null)
        {
            var jsonSerializer = new JavaScriptSerializer();
            var request = WebRequest.Create(requestURL) as HttpWebRequest;
            request.KeepAlive = true;
            request.ContentType = "application/json";
            request.Method = method;
            request.Headers.Add("Authorization", "Bearer " + token);

            if(requestBody != null)
            {
                Stream ws = request.GetRequestStream();
                using (var streamWriter = new StreamWriter(ws, new UTF8Encoding(false)))
                {
                    streamWriter.Write(requestBody);
                }
            }

            var response = request.GetResponse();
            var stream = new StreamReader(response.GetResponseStream());

            var googleEvent = Newtonsoft.Json.JsonConvert.DeserializeObject(stream.ReadToEnd().Trim());

            return googleEvent; 
        }

        private Event CreateGoogleEvent(string token, string calendarId, string requestBody)
        {
            var requestURL = string.Format("https://www.googleapis.com/calendar/v3/calendars/{0}/events", calendarId);
            return GoogleEventHandle(token, "POST", requestURL, requestBody);             
        }

Above is methods how we are accessing Google Calendar v3 API via webrequest. Now, we are be able to access Google Calendar API via OAuth. Nest step, we will create a simple CRUD UI by AngularJS.


HostForLIFE.eu ASP.NET MVC Hosting
HostForLIFE.eu revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24x7 access to their server and site configuration tools. Plesk completes requests in seconds. It is included free with each hosting account. Renowned for its comprehensive functionality - beyond other hosting control panels - and ease of use, Plesk Control Panel is available only to HostForLIFE's customers. They
offer a highly redundant, carrier-class architecture, designed around the needs of shared hosting customers.



European ASP.NET MVC Core Hosting :: Layout View ASP.NET Core MVC

clock November 28, 2019 07:58 by author Scott

Short tutorial only about Layout view in ASP.NET Core MVC. We will discuss about it. Let’s get started!

What is Layout?

The layouts are like the master pages in Webforms applications.  The common UI code, which can be used in many views can go into a common view called layout.

Why do we need Layout View in ASP.NET Core MVC?

Nowadays, almost all web applications have the following sections.

  • Website Header
  • Website Footer
  • Navigation Menus
  • Main Content Area

Please have a look at the following image which shows the above mentioned four areas on a website.

Instead of putting all the sections (i.e. the HTML) in each and every view pages, it is always better and advisable to put them in a layout view and then inherit that layout view in each and every view where you want that look and feel. With the help of layout views, now it is easier to maintain the consistent look and feel of your application. This is because if you at all need to do any changes then you need to do it only at one place i.e. in the layout view and the changes will be reflected immediately across all the views which are inherited from the layout view.

Layout View in ASP.NET Core MVC Application:

  1. Like the regular view in ASP.NET Core MVC, the layout view is also a file with a .cshtml extension
  2. If you are coming from ASP.NET Web Forms background, you can think the layout view as the master page in asp.net web forms application.
  3. As the layout views are not specific to any controller, so, we usually place the layout views in a subfolder called “Shared” within the “Views” folder.
  4. By default, in ASP.NET Core MVC Application, the layout view file is named _Layout.cshtml.
  5. The leading underscore in the file name indicates that these files are not intended to be served directly by the browser.
  6. In ASP.NET Core MVC, it is also possible to create multiple layout files for a single application. For example, you may have one layout file for the admin users and another layout file for non-admin users of your application.

How to Create a Layout View in ASP.NET Core MVC Application?

  1. In order to create a layout view in ASP.NET Core MVC, you need to follow the below steps.
  2. Right-click on the “Views” folder and then add a new folder with the name “Shared“.
  3. Next, Right-click on the “Shared” folder and then select the “Add” – “New Item” option from the context menu which will open the Add New Item window.
  4. From the “Add New Item” window search for Layout and then select “Razor Layout”, give a meaning full name (_Layout.cshtml) to your layout view and finally click on the “Add” button as shown below which should add _Layout.cshtml file within the Shared folder.

 

Note: In this article, I am going to show you how to create and use a layout file and in our upcoming articles, I will show you how to use website header, footer, and navigation menus.

Understanding the _Layout.cshtml file:

Let us have a look at the auto-generated HTML code in the _Layout.cshtml file. The following HTML is auto-generated in the _Layout.cshtml file.

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <div>
        @RenderBody()
    </div>
</body>
</html>

As you can see in the above layout file, it contains the standard Html, head, title and body elements. As the above elements are present in the layout file, so you don’t have to repeat all the above elements in each and every view.

The View or Page-specific title is retrieved by using the @ViewBag.Title expression. For example, when “index.cshtml” view is rendered using this layout view, then the index.cshtml view will set the Title property on the ViewBag. This is then retrieved by the Layout view using the expression @ViewBag.Title and set as the value for the <title> tag.

The @RenderBody() specifies the location where the view or page-specific content is injected. For example, if “index.cshtml” view is rendered using this layout view, then index.cshtml view content is injected at the location.

Let us modify the _Layout.cshtml page as shown below to include the header, footer, left navigation menus and main content area section.

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <table border="1" style="width:800px; font-family:Arial">
        <tr>
            <td colspan="2" style="text-align:center">
                <h3>Website Header</h3>
            </td>
        </tr>
        <tr>
            <td style="width:200px">
                <h3>Left Navigation Menus</h3>
            </td>
            <td style="width:600px">
                @RenderBody()
            </td>
        </tr>
        <tr>
            <td colspan="2" style="text-align:center; font-size:x-small">
                <h3>Website Footer</h3>
            </td>
        </tr>
    </table>
</body>
</html>

Modifying the Startup class:

Please modify the Startup class as shown below where we configure the required services for MVC.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace FirstCoreMVCApplication
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseMvcWithDefaultRoute();
        }
    }
}

Modifying the Home Controller:

Please modify the Home Controller as shown below.

using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCApplication.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Index()
        {
            return View();
        }       

        public ViewResult Details()
        {
            return View();
        }
    }
}

As you can see here we have created two action methods i.e. Index and View.

Using Layout view in ASP.NET Core MVC Application:

Now we are going to create the Index and Details views using the Layout view. In order to render a view using the layout view (_Layout.cshtml), you need to set the Layout property.

Index.cshtml:

Please modify the Index view as shown below to use the layout view.

@{
    ViewBag.Title = "Home Page";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Home Page</h1>

Details.cshtml:

Please modify the Details view as shown below to use the layout view.

@{
    ViewBag.Title = "Details Page";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Details Page</h1>

Now run the application and navigate to the Home/Index URL which should display the page as shown below.

If you don’t have a layout view for your website, then you need to repeat the required HTML for the above-mentioned sections in each and every view of your application. This is violating the DRY (Don’t Repeat Yourself) principle as we are repeating the same code in multiple views. As a result, it is very difficult to maintain the application. For example, if you have to remove or add a menu item from the list of navigation menus or even if you want to change the header or footer of your website then you need to do this in each and every view which is tedious, time-consuming as well as error-prone.



ASP.NET MVC Hosting UK - HostForLIFE.eu :: How to Use Automapper with ASP.NET MVC Application

clock November 8, 2019 11:20 by author Peter

At this moment, I will show you How to Use Automapper with ASP.NET MVC Application. Automapper could be a convention primarily based object - object mapper. it's offered in GitHub. Here I make a case for about a way to use Automapper to map between domain model objects and think about model objects in ASP.NET MVC applications.  Install Automapper to the project through Nuget.

Consider there's a powerfully typed view that expects a model object of type EmployeeViewModel. thus after querying with the Emplyee model object, we want to map this to EmployeeViewModel object.
public class Employee
   {
      public int EmployeeId { get; set; }
      public string EmployeeName { get; set; }
    }

And my employee view model
public class EmployeeViewModel
    {
        public int EmployeeId { get; set; }
        public string EmployeeName { get; set; }

    }

The use of AutoMapper
AutoMapper is designed within the web project. to form this more maintainable, create a folder (say Mappings) within the solution. Here we will produce 2 profile classes.  One for mapping from domain model object to look at model object and another one for reverse mapping.

public class DomainToViewModelMappingProfile : Profile
    {
        public override string ProfileName
        {
            get { return "DomainToViewModelMappings"; }
        }
        protected override void Configure()
        {
            Mapper.CreateMap<Employee, EmployeeViewModel>();
        }
    }
public class ViewModelToDomainMappingProfile : Profile
    {
        public override string ProfileName
        {
            get { return "ViewModelToDomainMappings"; }
        }
        protected override void Configure()
        {
            Mapper.CreateMap<EmployeeViewModel, Employee>();
        }
    }

Now create a configuration class within Mappings folder.
public class AutoMapperConfiguration
    {
        public static void Configure()
        {
            Mapper.Initialize(x =>
            {
                x.AddProfile<DomainToViewModelMappingProfile>();
                x.AddProfile<ViewModelToDomainMappingProfile>();
            });
        }
    }

And then call this configuration from global.asax.
AutoMapperConfiguration.Configure();

And from the controller simply map the employeeObject (domain model object) to employeeViewModelObject (view model object).
var employeeViewModelObject = Mapper.Map<Employee, EmployeeViewModel>(employeeObject);

In advanced situation we will even customise the configuration. for instance we will map a specific property from source to destination.
Mapper.CreateMap<X, XViewModel>()
.ForMember(x => x.Property1, opt => opt.MapFrom(source => source.PropertyXYZ));

Automapper provides extremely an improved and straightforward way to map between objects.



Silverlight 6 Hosting Netherlands - Cookie with JavaScript in Silverlight

clock November 1, 2019 11:07 by author Peter

Cookies are knowledge stored by the web browser, as easy as that. you'll be able to save something; yes I said anything, in cookies. I will conjointly do that through Silverlight itself, except for fun let's attempt doing it with JavaScript Silverlight 6. With this method we tend to follow, we'll be accessing JavaScript's function from Silverlight. This sometime becomes a headache for many developers.

The first step towards setting cookies through JavaScript, is to call the JavaScript function from Silverlight. Calling a JavaScript function from Silverlight is extremely straightforward. to know this, and more forthcoming things, produce a brand new Silverlight application "JavaScriptTweaks". Open JavaScriptTweaksTestpage.aspx, and add the subsequent code somewhere with <head> tag:
<script type="text/javascript">
    function SayHello()
   {
        alert("Hello!");
   }
</script>

Next step in the mainpage.cs inside the constructor add the code below:
HtmlPage.Window.Invoke("SayHello");
When you run the application, what you will see is a message box that pops up saying Hello at the very beginning of the app.

Now, we want to Setting the Cooking. Remove the SayHello function from the JavaScript. Write the following code:
function SetCookie(cookieName, cookieValue, Days)
{           
    var todayDate = new Date();
    var expireDate = new Date();
    if (Days == null || Days == 0) Days = 1;
    expire.setTime(todayDate.getTime() + 3600000 * 24 * Days);
    document.cookie = cookieName + ":" + cookieValue
    + ";expires=" + expireDate.toGMTString();          
}
Next step, call the function SetCookie with this code:
HtmlPage.Window.Invoke("SetCookie", "Name", "Peter", 5);


On the code above will call SetCookie function with the parameters cookieName "Name", cookieValue "Peter" and validity, in other words Days as "5". Line #5 of the function will set the expiry time period of cookies, which is in milliseconds and is about 432000000 for 5 days. Line #6 of the function will set the cookie's information like, its Name, Value and Expiry date. Our cookie is set to give information.

Now, we want to retrieve the information. Create three buttons in the XAML of the main page, 1 for each setcookie, getcookie and deletecookie.

Copy the function on the main page to the click event of the SetCookie Button.  And here is the code that I used:
function GetCookie(cookieName)
{
   var allcookies = document.cookie;
   // Get all the cookies in an array
   var cookiearray = allcookies.split(';');
   for (var i = 0; i < cookiearray.length; i++)
   {
       var nameOfCookie = cookiearray[i].split('=')[0];
       if (cookieName == nameOfCookie)
       {
           return cookiearray[i];
    }
 }
           return null;
}

Pass in the cookie name (which in our case is "Name") &  the function can return the entire cookie. On the GetCookie button select event and we should call this function. Write the following code:
private void ButtonGet_OnClick(object sender, RoutedEventArgs e)
{
    var cookie = HtmlPage.Window.Invoke("GetCookie", "Name");
    if (cookie == null)
    {
        MessageBox.Show("No cookie found");
        return;
    }
    MessageBox.Show(cookie.ToString().Split('=').LastOrDefault());
}

This will pop up a message box, showing the value of the cookie specified. Since I have my cookie as "name=Peter" it shows me "Peter".
Finally we want delete a cookie. You need to set the expiry date to a previous date. That can be done thorugh JavaScript's function as follows:
function DeleteCookie(cookieName)
{
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    document.cookie = cookieName + "=;expires=" + exp.toGMTString();
}
In the delete button click event call this function as:
private void ButtonDelete_OnClick(object sender, RoutedEventArgs e)
{
    HtmlPage.Window.Invoke("DeleteCookie", "Name");
}


Pass within the name of the cookie you wish to delete and bang! it'll be deleted. currently simply do this. Click on SetCookie, it'll set the cookie for you. now click on GetCookie to verify whether or not it did set a cookie or not, you ought to see the value of the cookie within the message box. Click on Deletecookie to delete the cookie. Finally click on Getcookie button once more, if everything worked fine then you ought to see a message within the message box saying: "No cookie found".

HostForLIFE.eu Silverlight 6 Hosting
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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC Hosting - HostForLIFE.eu :: ASP.NET MVC 5 Create Shared Razor Layout And ViewStart

clock October 25, 2019 09:18 by author Peter

In article, I have shared a way to create a Layout Razor and ViewStart in ASP.NET MVC 5.
 
Views/Shared
You need to create a shared folder, "Shared" in the Views directory.
 
Go Views/Shared directory and create new _LayoutPage1.cshtml file and write the following below code.
    <!DOCTYPE html> 
     
    <html> 
    <head> 
        <meta name="viewport" content="width=device-width" /> 
        <title>@ViewBag.Title</title> 
    </head> 
    <body> 
        <div> 
            @RenderBody() 
        </div> 
    </body> 
    </html> 


The @RenderBody()
Use display content in multiple controllers to View.

Example you can have a fixed header and footer in the page. Only change will be the content of the RenderBody() called in the code.
    <html> 
    <head> 
        <meta name="viewport" content="width=device-width" /> 
        <title>@ViewBag.Title</title> 
    </head> 
    <body> 
        <div class="header"> 
            <!--code header fixed--> 
        </div> 
        <div> 
            @RenderBody() 
        </div> 
        <div class="footer"> 
            <!--code footer fixed--> 
        </div> 
    </body> 
    </html> 


So you have fixed the (header/footer) for the website.
 
Okay, you need using _LayoutPage1.cshtml, so you to Views/Home/index.cshtml. Open it, pass the following below code.
    @{ 
        ViewBag.Title = "Index"; 
        Layout = "~/Views/Shared/_LayoutPage1.cshtml"; 
    } 


_ViewStart.cshtml used to define the layout for the website. You can set the layout settings as well, if HomeController is using Layout.
 
_LayoutHome.cshtml or AdminController is _LayoutAdmin.cshtml
    //Views/ViewStart.cshtml 
    @{ 
        Layout = "~/Views/Shared/_LayoutPage1.cshtml"; 
    } 


You can configuration _ViewStart.cshtml the following below code.
    @{ 
     
        string CurrentName = Convert.ToString(HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"]); 
        string clayout = ""; 
        switch (CurrentName) 
        { 
            case "Home": 
                clayout = "~/Views/Shared/_LayoutHome.cshtml"; 
                break; 
            default: 
                //Admin layout   
                clayout = "~/Views/Shared/_LayoutAdmin.cshtml"; 
                break; 
        } 
        Layout = clayout; 
     
    } 

This gives you an idea, how to use a Razor layout in various pages.

 



ASP.NET MVC 5 Hosting - HostForLIFE.eu :: What is And Why We Do State Management In ASP.NET MVC

clock October 17, 2019 11:58 by author Peter

If your website consists of multiple pages and you want to share the data appearing on the 2nd page to the 4th page, then you will have to use State Management feature of ASP.NET. Since our whole communication through the internet is done using HTTP Protocol and when a client(Browser) sends request to the server then it establishes a connection using HTTP and server gives the response, after that, connection will be disconnected. Actually each time a connection is created for a request and after the response it will be disconnected, which means if you have some data on first page and want to get it on the 10th, then it will be impossible to do it without state management feature. If you don’t use this feature then you will have to go the database for each single request(if you require data) which creates huge network traffic with increasing number of users.

You can manage the state by the following ways,

    Client Side State Management

        Cookie
        QueryString
        Hidden Form Field

    Server Side State Management

        Session
        TempData

Note
Client Side Management means nothing will be stored on server side but on client side and reverse will happen on server side. (i.e. all data will be on server side)
 
Client Side State Management
 
Cookie
 
Cookie is a text file with some information in it, generated by the most websites that you visit and then saved it in your browser(folder or subfolder) if you have enabled the cookie option.
 
Advantages

    All information is stored on client side.
    With cookie you can use the remember me option, some websites that you visit first time which then asks you or you can choose a language of your choice and then the information on website appears in that particular language every time you visit(depends upon expiry date). Also, you have seen some time, that this kind of option will work on your machine(laptop) not on your other devices, so behind the scenario there is a cookie.

Disadvantages

    You can disable cookies in your browser settings. This is a major drawback and if you have use cookies in your site for some features then it will cost you badly.
    Less secure since you can view the data in cookies by opening DevTools(in chrome)

Cookie types

    Persistent (Can specify expiry time)
    Non Persistent(Use for sessions and will expire as the browser or tab is closed in which the web app is opened)

The recommended Data limit: 4096bytes(4kb). Size should not exceed this value as you send data (>4KB) using cookie on every request, then more broadband is used because in some scenarios uploading speed can be lesser.
 
QueryString
 
With QueryString, you can specify the data in the URL tab.

    Starts with a question mark(?)
    If there are two values that you are sending, then it will be separated with &.

    There is no limit on length of queryString but the most recommended length for query string is 1024 characters. Try your queryString to be in that range because some web servers will through 413 error(Entity too long to respond)

Advantages

    Can’t be disabled by client
    Can be used to share information between pages and most suitable where the information is static(remains static for whole website)

    e.g.You request to go the specific page but the login is required and you fill the form successfully and then redirected to page where you were before login.

Disadvantages

    You require information on 4th page which is present on 1st page, then you will have to fetch the info again from the database and then send it(if the data is dynamic or changed in recent activity)
    The information that we send using QueryString gets visible to all users so it can’t be used to send sensitive data but if require then encrypt it then send.(an extra effort)

Hidden Field

    Share information between multiple requests on same page.
    If there is Single page application(SAP) or there is a page like login page where you given three attempts to user for entering right username and password then you can use it as a counter.

 
Advantages
 
Can’t be disabled by client.
 
Disadvantages
 
Need Encryption because the value can be seen by using DevTools of browser.



About HostForLIFE

HostForLIFE 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 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in