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

European ASP.NET MVC 5 Hosting - UK :: Creating Custom Scaffold Templates in ASP.NET MVC

clock November 27, 2015 18:59 by author Scott

Microsoft provides a powerful scaffolding engine for models in ASP.NET MVC applications that use Entity Framework. Scaffolding relieves web developers from the mundane task of writing the create, read, update, and delete (CRUD) code over and over again. The scaffolding engine uses T4 templates to generate basic controllers and views for models. However, scaffolded code is just a starting point, since it often needs to be customized to meet specific business requirements or satisfy specific design patterns.

In this blog post, I’ll provide a walkthrough on how to create project-specific custom scaffold templates for ASP.NET MVC. This can be a huge time-saver in applications with a large number of controllers and views. I will use Visual Studio 2013, ASP.NET MVC 5, Entity Framework 6, and C#.

SETUP

To get started, create a new ASP.NET MVC web application and add a simple Product model with the properties shown below and build the project.

namespace CustomScaffoldingDemo.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public bool IsDeleted { get; set; }
        public DateTime CreatedDate { get; set; }
        public DateTime UpdatedDate { get; set; }
    }
}

SCAFFOLDING CONTROLLER AND VIEWS

First, let’s use default templates to scaffold a controller and CRUD views for the Product model so we can review the results. To do so, right-click the Controllers folder in Solution Explorer and click Add New Scaffolded Item. In the Add Scaffold dialog, choose the MVC 5 Controller with views, using Entity Framework. On the Add Controller dialog, create a new data context and choose appropriate options that serve as parameters for the scaffolding engine. Then hit the Add button.

The scaffolding engine will use the default T4 templates to generate code for the controller and five views and add them to the appropriate folders. At this point you have full CRUD functionality for the Product model and can run the application.

As you review the generated code, you may notice that the scaffolding engine is intelligent enough to treat the Product ID properly by not scaffolding the editor for this property on the Create or Edit forms. You may also realize that the default templates do not meet the functional specification or your desired design patterns. For example, you may want to achieve the following:

–  Created Date and Updated Date properties should be set automatically by the system on create or update action respectively, and thus should not be editable on the Create and Edit views.
–  Products should be soft-deleted, so the Delete action of the Product controller must be changed to set the IsDeleted property and updating the Product instead of deleting it from the database. Index action should only return Products with IsDeleted set to false.
–  None of the views should display the IsDeleted property.
–  Views should use @ViewBag.Title as the page header instead of the view name. 
–  You may be using a Unit of Work pattern, so all calls to save changes to the database may need to be tweaked. 

You can manually make changes to the generated code, which has several drawbacks, including:

–  Typically, you would want most, if not all, controllers and views to be consistent across all models in your application. Making similar manual changes to controllers and views for all models is not an efficient approach.
–  When you make changes to a model, you will either have to scaffold these files again and lose your manual changes or manually update all views to match the updated model.

The best way to avoid manual changes and enforce consistency is to customize the scaffold templates.

CUSTOMIZING SCAFFOLD TEMPLATES

The original T4 templates used by the scaffolding engine are located in this folder: %programfiles%\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\Microsoft\Web\Mvc\Scaffolding\Templates.

While you can directly edit these templates, this will affect scaffolding for all future projects, which is not recommended. Instead, you can create project-specific copies of these templates so you can customize them. To do so, copy these templates into your MVC project’s CodeTemplates folder, following the same sub-folder structure. You only need to copy either C# or VB.NET templates, based on your project. The template filenames include the language they use. The convention is that the scaffolding engine uses the templates in the CodeTemplates project folder, if one exists, instead of the global templates.

Now you can modify these custom scaffold templates, which would affect scaffolded code only for this project. T4 templates are simply text files and can be edited directly in Visual Studio. Unfortunately, Visual Studio 2013 does not include a good T4 editor—there’s no syntax highlighting or IntelliSense. Fortunately, there are some third party add-on products that provide this functionality. Below is a screenshot of how the templates look in Visual Studio 2013. You can see I modified the header on line 26 to use @ViewBag.Title instead of the view name. 

<#@ template language="C#" HostSpecific="True" #>
<#@ output extension=".cshtml" #>
<#@ include file="Imports.include.t4" #>
@model <#= ViewDataTypeName #>
<#
// The following chained if-statement outputs the file header code and
// markup for a partial view, a view using a layout page, or a regular view.
if(IsPartialView) {
#> 

<#
} else if(IsLayoutPageSelected) {
#> 

@{
    ViewBag.Title = "<#= ViewName#>";
<#
if (!String.IsNullOrEmpty(LayoutPageFile)) {
#>
    Layout = "<#= LayoutPageFile#>";
<#
}
#&g
t;
}

@ViewBag.Title

To learn more about scaffolding check out this walkthrough from Microsoft. To learn more about T4 templates in general, start by reading this MSDN article



European ASP.NET MVC 5 Hosting :: How to Use AngularJS in ASP.NET MVC

clock November 12, 2015 20:18 by author Scott

In this short tutorial, I will show how to use AngularJS in ASP.NET MVC. I hope that you enjoy this short tutorial and this is helpful.

Application Inception

While Angular is a framework for the modern Single Page App, I have found that a lot of our MVC applications call for a collection of these “ng-apps”. In this instance they typically don’t include the client side routing.

Please See Sample Application

The image to the right is the file structure for a sample airplane scheduling app. There are three sections:

  Home (simple js) - A simple calendar showing flights
  Details (angular) - Information about a single flight
  Manage (angular) - A place for settings, pilots, etc...

Bundle Configuration

While asset bundling is a great feature of ASP.Net, it is easy to get carried away. When I came on there were a lot of projects that just included all the js files for the entire application in a single ScriptBundle. This was one of the first places I set my sights.

I decided that a lot of the services would be shared, so they could go in their own Angular module and in their own ASP Bundle. Then each mini-app could get it’s own module and bundle. Lets take a look at theBundleConfiguration.cs file.

using System.Web.Optimization;

namespace Jobney.App.Web
{
    public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/js-base").Include(
                        "~/Scripts/libs/jquery-{version}.js",
                        "~/Scripts/libs/bootstrap.js",
                        "~/Scripts/libs/select2.js",
                        "~/Scripts/libs/bootstrap-datepicker.js",
                        "~/Scripts/libs/respond.js",
                        "~/Scripts/libs/lodash.js",
                        "~/Scripts/endless.js"
                        ));

            bundles.Add(new ScriptBundle("~/bundles/ng-base").Include(
                        "~/Scripts/libs/angular/angular.js",
                        "~/Scripts/libs/angular/ui-router.js",
                        "~/Scripts/libs/angular/ui-bootstrap-custom-0.9.0.js",
                        "~/Scripts/libs/angular/ui-bootstrap-custom-tpls-0.9.0.js",
                        "~/Scripts/libs/angular/angular-animate.js",
                        "~/Scripts/libs/angular/toaster.js"
                        ));

            bundles.Add(new ScriptBundle("~/bundles/ng-shared-services")
                .IncludeDirectory("~/Scripts/apps/shared/", "*.js"));

            bundles.Add(new ScriptBundle("~/bundles/ng-manage-app")
                .IncludeDirectory("~/Scripts/apps/manage/","*.js"));

            bundles.Add(new ScriptBundle("~/bundles/ng-tripinfo-app")
                .Include(
                    "~/Scripts/libs/jquery-ui.js",
                    "~/Scripts/libs/angular/sortable.js",
                    "~/Scripts/libs/angular/select2.js",
                    "~/Scripts/libs/angular/ngAutocomplete.js"
                )
                .IncludeDirectory("~/Scripts/apps/tripinfo/", "*.js"));

            bundles.Add(new StyleBundle("~/Content/css/base").Include(
                      "~/Content/css/bootstrap.css",
                      "~/Content/css/datepicker3.css",
                      "~/Content/css/select2.css",
                      "~/Content/css/toaster.css",
                      "~/Content/css/select2-bootstrap.css",
                      "~/Content/css/font-awesome.css"
                    ));
            bundles.Add(new StyleBundle("~/Content/css/custom").Include(
                      "~/Content/css/endless.css",
                      "~/Content/css/endless-skin.css",
                      "~/Content/css/site.css"));
        }
    }
}

Then using the bundles, say in the manage app, it would look like this:

@model Jobney.Casm.Web.Models.ManageDataBootstrapper
<div data-ng-app="Jobney.Casm.ManageApp" data-ng-controller="ManageAppCtrl">
    <ul class="tab-bar grey-tab">
        <!-- content here -->
    </ul>

    <div data-ui-view></div>
</div>

@section scripts
{
    <!-- Start ng-base -->
    @Scripts.Render("~/bundles/ng-base")

    <!-- Start ng-shared-services -->
    @Html.Partial("_SharedServices")

    <!-- Start ng-manage-app -->
    @Html.Partial("_ManageAppSetup", Model)
}

Services Need Data And Data Needs Urls

As an ASP.Net MVC developer, you are probably used to letting the routing engine create urls for you when you need them. And why not? Who knows what crazy routing constraints the client/pm/other developers decided needed to be in your application. And with Razor helpers, this is pretty easy. Angular shouldn’t have to try hard to figure out those rules. So how do we combine these two worlds?

@section scripts
{
    app.constant('RouteConfig', {
        base: '@Url.Content("~/")',
        project: {
            all: '@Url.Action("All", "Project")',
            details: '@Url.Action("Details", "Project")',
            post: '@Url.Action("Post", "Project")'
        },
        vendor: {
            category: '@Url.Action("GetByCategory", "Vendor")',
            details: '@Url.Action("GetById", "Vendor")',
            getProductRating: '@Url.Action("GetByProduct", "Rating")'
        },
        resolve: function (url) {
            return this.base + url;
        }
    });
}

Such http. Many calls.

In the manage app we are going to need some data. When the situation calls for it, I don’t mind sending that data down with the app. I think I took this idea from John Papa or one of those PluralSight authors. Basically, I just use JSON.Net to serialize my dataset on the page. Let’s take a look at it.

@model Jobney.Casm.Web.Models.ManageDataBootstrapper

<script>
    (function () {
        'use strict';

        var app = angular.module('Jobney.Casm.ManageApp', [
            'ui.router',
            'ui.bootstrap',
            'Jobney.Casm.SharedServices'
        ]);

        app.factory('BootstrappedData', [function() {
            var service = {};

            service.pilots = @Html.Raw(Model.Pilots);
            service.passengers = @Html.Raw(Model.Passengers);
            service.airplanes = @Html.Raw(Model.Airplanes);
            service.settings = @Html.Raw(Model.Settings);

            return service;
        }]);       

    })();
</script>

@Scripts.Render("~/bundles/ng-manage-app")

 



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