European ASP.NET MVC Hosting

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

ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Dynamic Auto Complete in MVC for any Table of DataBase

clock October 25, 2016 09:14 by author Peter

Today, I will tell you about Dynamic Auto Complete in MVC for any Table of DataBase. With the following code, we can file record of product code on the basis of product name. Now write the code below:

View
@model string < input type = "hidden" 
id = "TableName_@Model" 
value = "@Model" / > @Html.TextBox("txtCode_" + @Model) 
@Html.TextBox("txtName_" + @Model) < script type = "text/javascript" > $(function () 

    $('#txtName_@Model').autocomplete( 
    { 
        source: function (request, response) 
        { 
            alert("hi"); 
            var id = $('#TableName_@Model').val(); 
            $.ajax( 
            { 
                url: "/Common/AutocompleteName/" + id + "?name=" + $('#txtName_@Model').val(), 
                dataType: "json", 
                type: 'POST', 
                data: 
                { 
                    name: request.term 
                }, 
                success: function (data) 
                { 
                    response(data); 
                } 
            }); 
        }, 
        autoFocus: true, 
        select: function (event, ui) 
        { 
            var id = $('#TableName_@Model').val(); 
            var mData; 
            var unit; 
            $.ajax( 
            { 
                url: "/Common/GetCodeName/" + id, 
                type: 'POST', 
                data: 
                { 
                    codeName: ui.item.value, 
                    mPara: 'N' 
                }, 
                success: function (_result) 
                { 
                    // alert(_result); 
                    mData = _result.UserName; 
                    unit = _result.unitdata; 
                    setTimeout(function () 
                    { 
                        $('#txtCode_@Model').val(mData); 
                    }, 1000); 
                    $('#Description_@Model').val(mData); 
                    $('#Units_@Model').html(unit); 
                } 
            }); 
        }, 
        minLength: 1 
    }); 
    $('#txtCode_@Model').autocomplete( 
    { 
        source: function (request, response) 
        { 
            var id = $('#TableName_@Model').val(); 
            $.ajax( 
            { 
                url: "/Common/AutocompleteCode/" + id + "?code=" + $('#txtCode_@Model').val(), 
                dataType: "json", 
                data: 
                { 
                    code: request.term 
                }, 
                success: function (data) 
                { 
                    response(data); 
                }, 
                type: 'POST' 
            }); 
        }, 
        autoFocus: true, 
        select: function (event, ui) 
        { 
            var id = $('#TableName_@Model').val(); 
            var mData; 
            var unit; 
            $.ajax( 
            { 
                url: "/Common/GetCodeName/" + id, 
                type: 'POST', 
                data: 
                { 
                    codeName: ui.item.value, 
                    mPara: 'C' 
                }, 
                success: function (_result) 
                { 
                    unit = _result.unitdata; 
                    mData = _result.UserName; 
                    setTimeout(function () 
                    { 
                        $('#txtName_@Model').val(mData); 
                    }, 1000); 
                    $('#Units_@Model').html(unit); 
                    $('#Description_@Model').val(mData); 
                } 
            }); 
        }, 
        minLength: 1 
    }); 
}); < /script> 
Controller-- -- -- -- -- -- -- -- -- -- -- --[HttpPost] 
public JsonResult AutocompleteName(string id, string name) 

    var TblSet = Core.CoreCommon.GetTableData(id); 
    var output = TblSet.AsQueryable().ToListAsync().Result.ToList(); 
    Dal.TFAT_WEBERPEntities context = new Dal.TFAT_WEBERPEntities(); 
    return Json(from m in output where m.GetType().GetProperty("Name").GetValue(m).ToString().Contains(name) select m.GetType().GetProperty("Name").GetValue(m).ToString()); 
    } 
    [HttpPost] 
public JsonResult AutocompleteCode(string id, string code) 
    { 
        var TblSet = Core.CoreCommon.GetTableData(id); 
        var output = TblSet.AsQueryable().ToListAsync().Result.ToList(); 
        return Json(from m in output where m.GetType().GetProperty("Code").GetValue(m).ToString().Contains(code) select m.GetType().GetProperty("Code").GetValue(m).ToString()); 
    } 
    [HttpPost] 
public ActionResult GetCodeName(string id, string codeName, string mPara) 

    var TblSet = Core.CoreCommon.GetTableData(id); 
    var output = TblSet.AsQueryable().ToListAsync().Result.ToList(); 
    Dal.TFAT_WEBERPEntities context = new Dal.TFAT_WEBERPEntities(); 
    string UserName = ""; 
    string unitdata = ""; 
    string Product = ""; 
    if (mPara == "C") 
    { 
        var query = (from m in output where m.GetType().GetProperty("Code").GetValue(m).ToString().Contains(codeName) select m.GetType().GetProperty("Name").GetValue(m).ToString()); 
        if (id == "ItemMaster") 
        { 
            var query1 = (from m in output where m.GetType().GetProperty("Code").GetValue(m).ToString().Contains(codeName) select m.GetType().GetProperty("Unit").GetValue(m).ToString()); 
            var NewQuery = (from c in output where c.GetType().GetProperty("Code").GetValue(c).ToString().Contains(codeName) select c.GetType().GetProperty("Name").GetValue(c).ToString()); 
            if (query1 != null) 
            { 
                unitdata = query1.First().ToString(); 
            } 
            if (NewQuery != null) 
            { 
                Product = NewQuery.First().ToString(); 
            } 
        } 
        if (query != null) 
        { 
            UserName = query.First().ToString(); 
        } 
    } 
    else 
    { 
        var query = (from m in output where m.GetType().GetProperty("Name").GetValue(m).ToString().Contains(codeName) select m.GetType().GetProperty("Code").GetValue(m).ToString()); 
        if (query != null) 
        { 
            UserName = query.First().ToString(); 
        } 
    } 
    return Json(new 
    { 
        UserName, 
        unitdata, 
        Product 
    }); 
    // return Content(UserName); 

Common Class-- -- -- -- -- -- -- -- -- - public class CoreCommon 

    public static object GetTableObject(string TableName) 
    { 
        Type mType = BuildManager.GetType(string.Format("TFATERPWebApplication.Dal.{0}", TableName), true); 
        return System.Activator.CreateInstance(mType); 
    } 
    public static Type GetTableType(string TableName) 
    { 
        return BuildManager.GetType(string.Format("TFATERPWebApplication.Dal.{0}", TableName), true); 
    } 
    public static DbSet GetTableData(string tablename) 
    { 
        var mType = BuildManager.GetType(string.Format("TFATERPWebApplication.Dal.{0}", tablename), true); 
        TFAT_WEBERPEntities ctx = new TFAT_WEBERPEntities(); 
        return ctx.Set(mType); 
    } 
    public static string GetString(string[] col) 
    { 
        StringBuilder sb = new StringBuilder(); 
        foreach(string s in col) 
        { 
            sb.Append(s); 
            sb.Append(","); 
        } 
        return sb.ToString().Substring(0, sb.Length - 1); 
    } 

HostForLIFE.eu ASP.NET MVC 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 6 Hosting - HostForLIFE.eu :: How to Registering Custom Directories For Views In ASP.NET MVC?

clock October 11, 2016 20:54 by author Peter

In this post, I will show you how to Registering Custom Directories For Views In ASP.NET MVC 6. In ASP.NET MVC by default or convention is when we create application, our Views reside in Views directory for our Controller actions. For Example, by default it create Home controller with Index action, and if we see in Solution Explorer in Views directory we can see directory Views, Home, then Index.cshtml and we have it's action like the following code snippet:

    publicclassHomeController: Controller 
    { 
        public ActionResult Index() 
        { 
            return View(); 
        } 
    } 

And we have this action's Views in Views folder as in the following screen:

Now by default it will first look for Index.cshtml file in Views/Home folder and if it is unable to find it there then it will find in View/Shared folder. If it do not find there, then an exception will be thrown that view file is not found. Here is the exception text which is thrown:

The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:
    ~/Views/Home/Index.aspx
    ~/Views/Home/Index.ascx
    ~/Views/Shared/Index.aspx
    ~/Views/Shared/Index.ascx
    ~/Views/Home/Index.cshtml
    ~/Views/Home/Index.vbhtml
    ~/Views/Shared/Index.cshtml
    ~/Views/Shared/Index.vbhtml


See:

The same is the case for partial view when we call return PartialView(), it first looks in the respective controller's Views/Home directory in the case of HomeController and in case of failure it looks in the View/Shared folder.

Now what if we had made a separate directory for partial views in my Views folder and Shared folder like:

Views/Home/Partials and Views/Shared/Partial then we have to tell the ViewEngineto look in that directory as well by writing the following code in Gloabl.asaxfileinApplication_Startevent.

For example, we have this code and we are returning _LoginPartial.cshtml from Index action of HomeController, now what will happen it will look in View/Home directory first and in failure it will look in View/Shared, but this time we have my partial views in separate directory named Partial for every controller and for shared as well, In this case HomeController partial views are in Views/Home/Partials and in Views/Shared/Partials:

    publicclassHomeController: Controller 
    { 
        public ActionResult Index() 
        { 
            return View(); 
        } 
    } 


In this case also we will get the same exception as Engine will not be able to find the View file _LoginPartial.cshtml.
 
The beauty of asp.net mvc framework is the  extensiblity which you can do according to your needs and business requirements, one of them is that  if you want your own directories structure for organizing your views you can register those directories with razor view engine, doing that will make your life easy as you will not have to specify fully qualified path of the view, as razor will know that it needs to look for the view in those directories as well which you have registered with it.
 
So what we have to do is to register this directory pattern in the application so that every time we call any View it should look in those directories as well in which we have placed the View files. So here is the code for that.

    publicclassMvcApplication: System.Web.HttpApplication 
    { 
        protectedvoidApplication_Start() 
        { 
            AreaRegistration.RegisterAllAreas(); 
            WebApiConfig.Register(GlobalConfiguration.Configuration); 
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
            RouteConfig.RegisterRoutes(RouteTable.Routes); 
            BundleConfig.RegisterBundles(BundleTable.Bundles); 
            AuthConfig.RegisterAuth(); 
            RazorViewEnginerazorEngine = ViewEngines.Engines.OfType < RazorViewEngine > ().FirstOrDefault(); 
            if (razorEngine != null) 
            { 
                varnewPartialViewFormats = new [] 
                { 
                    "~/Views/{1}/Partials/{0}.cshtml", 
                    "~/Views/Shared/Partials/{0}.cshtml" 
                }; 
                razorEngine.PartialViewLocationFormats = razorEngine.PartialViewLocationFormats.Union(newPartialViewFormats).ToArray(); 
            } 
        } 
    } 

Now whenever we will call return PartialView("SomeView") it will look in that Controller Views directory's subdirectory named Partials as well and in case it not finds there it will look in both Views/Shared and Views/Shared/Partials.

The same way you can register other directories or your own Custom directory structure if you need to, so doing this way you will not need to specify complete path for like return View("~/Views/Shared/Paritals/Index.cshtml"), instead you can just write then return View() if you want to load Index View and your action name is also Index which is being called, or if you want some other view to be rendered or some other action is invoked and you want to return Index view then you can write return View("Index").

 

HostForLIFE.eu ASP.NET MVC 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.



European ASP.NET MVC 6 Hosting - HostForLIFE.eu :: ASP.NET MVC 6 Dependency Injection

clock October 5, 2016 23:32 by author Scott

Dependency injection (DI) has been possible in previous versions of MVC. With each new version DI has been easier to implement and, with MVC6, DI is supplied right out of the box. In this article we’ll look at how the new DI implementation works, what are its weaknesses and how we can replace it with our favorite DI framework.

What’s new

The unification of APIs across ASP.NET is a common theme throughout ASP.NET 5, and dependency injection is no different. The new ASP.NET stack including: MVC, SignalR and Web API, etc. rely on a built-in minimalistic DI container. The core features of the DI container have been abstracted out to the IServiceProvider interface and are available throughout the stack. Because the IServiceProvider is the same across all components of the ASP.NET framework a single dependency can be resolved from any part of the application.

The DI container supports just 4 modes of operation:

  • Instance – a specific instance is given all the time. You are responsible for its initial creation.
  • Transient – a new instance is created every time.
  • Singleton – a single instance is created and it acts like a singleton.
  • Scoped – a single instance is created inside the current scope. It is equivalent to Singleton in the current scope.

BASIC SETUP

Let’s walk through setting up DI in a MVC application. To demonstrate the basics, we’ll resolve the dependency for the service used to get project data. We don’t need to know anything about the service other than that it implements the IProjectService interface, an interface custom to our demo project. IProjectService has one method,GetOrganization(), that method retrieves an organization and its corresponding list of projects.

public interface IProjectService
{
    string Name { get; }
    Organization GetOrganization();
}

public class Organization
{
    public string Name { get; set; }
    [JsonProperty("Avatar_Url")]
    public string AvatarUrl { get; set; }
    public IQueryable<Project> Projects { get; set; }
}

We’ll use the IProjectService to get the organization data and display it in a view. Let’s start by setting up the controller where the service will be used. We’ll use constructor injection by creating a new constructor method for our controller that accepts anIProjectService. Next, the Index action will callGetOrganization, sending the data to the view to be rendered.

private readonly IProjectService projectService;
public HomeController(IProjectService projectService)
{
    this.projectService = projectService;
}
public IActionResult Index()
{
    Organization org = projectService.GetOrganization();
    return View(org);
}

If we try to run the application at this point we’ll receive an exception because we haven’t yet added a concrete implementation of ourIProjectService to the DI container.

InvalidOperationException: Unable to resolve service for type 'DependencyInjectionMVC6Demo. Services. IProjectService' while attempting to activate 'DependencyInjectionMVC6Demo. Controllers. HomeController'.
Microsoft. Framework. DependencyInjection. ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)

The exception message shows that the code fails during a call toActivatorUtilities.GetService. This is valuable information because it shows that in MVC6 the DI container is already involved in the controller’s construction. Now we just need to tell the container how to resolve the dependency.

In order to resolve the dependency, we need a concrete implementation ofIProjectService. We’ll add a DemoService class and, for simplicity, it will use static dummy data.

public class DemoService : IProjectService
{
    public string Name { get; } = "Demo";

    public Organization GetOrganization() => new Organization
    {
        Name = this.Name,
        AvatarUrl = $"http://placehold.it/100&text={this.Name}",
        Projects = GetProjects()
    };

private IQueryable<Project> GetProjects() => new List<Project> {
         new Project {
             Id = 0,
             Description = "Test project 0",
             Name = "Test 0",
             Stars = 120
         },
         //...
         new Project {
             Id = 4,
             Description = "Test project 4",
             Name = "Test 4",
             Stars = 89
         }
    }.AsQueryable();
}

Finally, we’ll instruct the DI container to instantiate a new DemoServicewhenever IProjectService is required. To configure the container we’ll modify the ConfigureServices method in Startup.cs. Our configuration will be added to the end of this method.

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    //... other services
    // Add MVC services to the services container.
    services.AddMvc();

    //our services
}

The service is added by using the AddTransient extension method on the services collection, and setting the IProjectService as the type of service and the DemoService as the implementation.

public void ConfigureServices(IServiceCollection services)
{
    //... other services
    // Add MVC services to the services container.
    services.AddMvc();

    //our services
    services.AddTransient<IProjectService, DemoService>();
}

With the service added, DemoService will now be instantiated when the controller is created, and the exception will no longer be thrown.



European ASP.NET MVC Hosting - HostForLIFE.eu :: Tag Helpers in ASP.NET Core

clock September 29, 2016 21:44 by author Scott

What's a Tag Helper?

It's a set of code that allows you to no longer have to use Razor helpers to build your cshtml forms. What this means is that when you had to write this:

@Html.ActionLink("Add a Movie", "Add", "Movie")

You can now write this:

<a asp-action="Add" asp-controller="Movie">Add a Movie</a> 

Because of this, you can now write views that look like HTML rather than an unwieldy mix of HTML and C#.

The Completed Form

I like to show the results first. Here's the view model we will be using:

public class AddMovieVM 
{
    [Required(ErrorMessage = "Please enter a title for this movie.")]
    [Display(Name = "Title:")]
    public string Title { get; set; }

    [Required(ErrorMessage = "Please select a release date for this movie.")]
    [Display(Name = "Release Date:")]
    public DateTime ReleaseDate { get; set; }

    [Required(ErrorMessage = "Please enter a running time for this movie")]
    [Range(1, 1000, ErrorMessage = "The running time must be between 1 and 1000 minutes.")]
    [Display(Name = "Running Time:")]
    public int RunningTime { get; set; }

    [Display(Name = "Description:")]
    public string Description { get; set; }

    [Display(Name = "Genre:")]
    public int SelectedGenre { get; set; }

    public List<SelectListItem> AllGenres { get; set; }
}

Now, if we were using HTML Helpers, our corresponding Add view might look like this:

@model MoreTagHelpers.ViewModels.AddMovieVM

<h2>Add a Movie</h2> 
@Html.ActionLink("Back to Movies", "Add", "Movie")
@using (Html.BeginForm("Add", "Movie"))
{
    <div>
        <div>
            @Html.LabelFor(x=>x.Title)
            @Html.TextBoxFor(x=>x.Title)
            @Html.ValidationMessageFor(x=>x.Title)
        </div>
        <div>
            @Html.LabelFor(x => x.ReleaseDate)
            @Html.TextBoxFor(x => x.ReleaseDate, new { @type = "date" })
            @Html.ValidationMessageFor(x => x.ReleaseDate)
        </div>
        <div>
            @Html.LabelFor(x => x.RunningTime)
            @Html.TextBoxFor(x => x.RunningTime, new { @type = "number" })
            @Html.ValidationMessageFor(x => x.RunningTime)
        </div>
        <div>
            @Html.LabelFor(x => x.Description)
            @Html.TextAreaFor(x => x.Description)
            @Html.ValidationMessageFor(x => x.Description)
        </div>
        <div>
            @Html.LabelFor(x=>x.SelectedGenre)
            @Html.DropDownListFor(x => x.SelectedGenre, Model.AllGenres)
            @Html.ValidationMessageFor(x => x.SelectedGenre)
        </div>
        <div>
            <input type="submit" value="Save" />
        </div>
    </div>
}

Now, here's that same form, using Tag Helpers.

@model MoreTagHelpers.ViewModels.AddMovieVM

<h2>Add a Movie</h2> 
<a asp-action="Index" asp-controller="Movie">Back to Movies</a> 
<form asp-action="Add" asp-anti-forgery="true" asp-controller="Movie"> 
    <div>
        <div>
            <label asp-for="Title"></label>
            <input type="text" asp-for="Title" />
            <span asp-validation-for="Title"></span>
        </div>
        <div>
            <label asp-for="ReleaseDate"></label>
            <input type="date" asp-for="ReleaseDate" />
            <span asp-validation-for="ReleaseDate"></span>
        </div>
        <div>
            <label asp-for="RunningTime"></label>
            <input type="number" asp-for="RunningTime" />
            <span asp-validation-for="RunningTime"></span>
        </div>
        <div>
            <label asp-for="Description"></label>
            <textarea asp-for="Description"></textarea>
            <span asp-validation-for="Description"></span>
        </div>
        <div>
            <label asp-for="SelectedGenre"></label>
            <select asp-for="SelectedGenre" asp-items="Model.AllGenres"></select>
            <span asp-validation-for="SelectedGenre"></span>
        </div>
        <div>
            <input type="submit" value="Save" />
        </div>
    </div>
</form> 

HTML all the things! That second form is much cleaner than the first IMHO. But, what really makes it is that Visual Studio will highlight which HTML tags are using tag helpers:

 

 

The normal HTML is highlighted regularly, and the tag helper HTML is in purple, making it really obvious which is which and hopefully negating some of the complaints I've seen about Razor being more obvious than Tag Helpers.

Let's dive into some of these helpers to see how you can use them in your ASP.NET MVC 6 projects.

Anchor Tag Helper

First, let's look at this helper:

<a asp-action="Index" asp-controller="Movie">Back to Movies</a> 

That's just an anchor tag with two tag helper attributes. Notice that each tag helper attribute begins with "asp-", and their names make intrinsic sense to us: "action" and "controller".

In the particular case of the anchor tag helper, there's a few other properties we could set, like asp-fragment, asp-route, and asp-path. Even better, Visual Studio now gives you intellisense for these attributes:

Form Tag Helper

The form tag helper looks something like this:

<form asp-action="Add" asp-anti-forgery="true" asp-controller="Movie"></form> 

The properties "asp-action" and "asp-controller" are same as in the anchor tag helper, but notice the "asp-anti-forgery" property. Setting this to true is the same as using the @Html.AntiForgeryToken helper in Razor. This helper has simply made your views a little bit cleaner.

Label Tag Helper

Making your views a little bit cleaner is a theme you'll see woven into each of the tag helpers, and the next example comes with the label tag helper. Here's our example:

<label asp-for="Title"></label> 

Input Tag Helper

Continuing with the simple theme:

<input type="text" asp-for="Title" /> 

Now there are many different kinds of input tags (e.g. date, checkbox, text, radio, etc.) and each kind had a different Razor helper. In the new tag helpers, there's just the input tag helper, with two attributes: "asp-for" and "asp-format".

TextArea Tag Helper

The text area is a separate tag in HTML. Here's the helper for it:

<textarea asp-for="Description"></textarea> 

Select Tag Helper

Another tag which is different from the standard input tag is the select tag, and consequently it has a different tag helper:

<select asp-for="SelectedGenre" asp-items="Model.AllGenres"></select> 

Again we see "asp-for" but now we also see the source collection specified using "asp-items." Easy. One odd thing I noticed about this is that "asp-for" doesn't require the Model. prefix, but "asp-items" does. If anybody knows why this is, I'd love to hear it.

Validation Tag Helper

The final tag helper we see on the completed form above is the one on a <span> tag. This is an unusual one, since under many circumstances you won't want to use a span tag as anything other than a <span>.

Except when what you want is a validation message. In that case, you'd use this:

<span asp-validation-for="Description"></span> 

This is the time when we should show the HTML that this renders:

<span class="field-validation-valid" data-valmsg-for="SelectedGenre" data-valmsg-replace="true"></span> 

But wait, that's not all! There are several other helpers we can use.

Environment Tag Helper

Here's one of those other helpers:

<environment names="Development"> 
...
</environment> 
<environment names="Staging,Production"> 
...
</environment> 

This helper is really interesting because the contents of the helper only get rendered if the HTML is deployed into specific environments. It does this by looking at an environment variable called ASPNET_ENV, and which you can set by right-clicking on the Project file and selecting Properties, then selecting Debug.

I'm hoping there's an easier way to change this variable in the fully-released version of Visual Studio, but until then, this is how you use it.

Link and Script Tag Helpers

These are possibly the most interesting new helpers.

<link rel="stylesheet" href="//ajax.aspnetcdn.com/ajax/bootstrap/3.0.0/css/bootstrap.min.css" 
asp-fallback-href="~/lib/bootstrap/css/bootstrap.min.css" asp-fallback-test-class="hidden" asp-fallback-test-property="visibility" asp-fallback-test-value="hidden" />

<script src="//ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.js" asp-fallback-src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js" asp-fallback-test="window.jQuery"></script> 

There's a lot going on here. First, notice the values in the src attribute. Those urls point to the Microsoft Ajax CDN, a new (to me, at least) content-delivery network that holds many commonly-used production CSS and JS files, particularly those produced and maintained by Microsoft. In our case, in the sample project we get the script files for jQuery, unobtrusive validation, bootstrap, and others.

But what about those "asp-fallback-src" attributes? They specify a second location that we can go grab the source files from should the first location be unavailable. In other words, we now have a fallback plan that allows our CSS and JS files to gracefully degrade over should the CDN (if we are using one) not be available. Finally, note that the fallback parameters are entirely optional.

Image Tag Helper

New in the Beta 5 release of ASP.NET is the Image Tag Helper which looks like this:

<img src="~/content/images/profile.jpg" 
     alt="John Smith"
     asp-append-version="true" />

Notice the new asp-append-version attribute; that's the only TagHelper attribute in this tag. What that does is render an <img> with a query string attribute appended on the source URL, like this:

<img src="/content/images/profile.jpg?v=X5q6D366_nQ2fQqUso0F24gWy2ZekXjHz83KmWyaiOOk" 
     alt="company logo"/>

The content of the v attribute is determined by the content of the image; if the content of the image changes, so does the v attribute. This forces the browser to download the image again.

This is a technique known as cache busting; writing code that forces the browser to download a resource (in this case, an image) if that resource changes. This technique guarantees that the user will always get the most recent version of the resource.

Cache Tag Helper

The Cache tag helper is similar to the Environment tag helper in that it doesn't target a specific HTML tag. Rather, it caches its contents in server-side memory, set to an expiration date. An example might look like this:

<cache expires-after="@TimeSpan.FromMinutes(5)" vary-by-user="true"> 
    @Html.Partial("WeatherReport")
</cache> 

In this sample, the WeatherReport partial view will be cached for 5 minutes, and will vary by the user. We can do this to significantly reduce load on the server as all of these requests will be cached server-side.

What actually happens is that ASP.NET generates an ID that is unique to the context of the cached content, which allows you to have multiple <cache> on a single page and not have them interfere with one another.

There are quite a few ways to control how the cache operates. Attributes include expires-after, expires-on, expires-sliding, vary-by-user, vary-by-query, vary-by-route, etc. You can use any combination of vary-by-* attributes on a single cache tag, and doing so modifies the ID that is generated for the cache.

There's one major limitation to this tag: on the back end, it uses a construct called MemoryCache to store the cached content. MemoryCache is limited by the amount of memory available; once there's not enough memory to go around, MemoryCache will purge items until it has the memory necessary. Further, any app pool reset or server shutdown will destroy this cache. Basically, don't treat MemoryCache like a persistent storage solution, because it is not such a thing.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: CRUD Example with ASP.NET MVC and SQL Server

clock September 6, 2016 19:44 by author Peter

Today, let me show you a CRUD example with ASP.NET MVC and SQL Server. This sample demonstrates how to use the CRUD (Create, Read, Update delete) record in MVC in Visual Studio. We are using SQL server database for this demo.

CrudController .cs
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
using CurdMvc.Models; 
using System.Data; 
using System.Configuration; 
using System.Data.SqlClient; 
namespace CurdMvc.Controllers 

    public class CurdController: Controller 
    { 
        // 
        // GET: /Curd/ 
        SqlConnection con = new SqlConnection("Data Source=BITS-PC;Initial Catalog=TestDB;Integrated Security=True"); 
        public ActionResult Index() 
            { 
                List < CurdModel > lstRecord = new List < CurdModel > (); 
                SqlDataReader dr = null; 
                SqlCommand command = new SqlCommand("GetAllRecordSP", con); 
                command.CommandType = CommandType.StoredProcedure; 
                con.Open(); 
                dr = command.ExecuteReader(); 
                while (dr.Read()) 
                { 
                    CurdModel mdl = new CurdModel(); 
                    mdl.id = Convert.ToInt32(dr["Id"]); 
                    mdl.email = dr["Email"].ToString(); 
                    mdl.name = dr["Name"].ToString(); 
                    lstRecord.Add(mdl); 
                } 
                con.Close(); 
                return View(lstRecord); 
            } 
            [HttpGet] 
        public ActionResult Add(int ? id) 
            { 
                CurdModel mdl = new CurdModel(); 
                if (id != null) 
                { 
 
                    SqlCommand cmd = new SqlCommand("GetRecordByIdSP", con); 
                    cmd.CommandType = CommandType.StoredProcedure; 
                    cmd.Parameters.Add("@Id", SqlDbType.Int).Value = id; 
                    SqlDataReader dr = null; 
                    con.Open(); 
                    dr = cmd.ExecuteReader(); 
 
                    DataTable dt = new DataTable(); 
                    dt.Load(dr); 
 
                    mdl.id = Convert.ToInt32(dt.Rows[0][0].ToString()); 
                    mdl.name = dt.Rows[0][1].ToString(); 
                    mdl.email = dt.Rows[0][2].ToString(); 
                    con.Close(); 
                    return View(mdl); 
                } 
                return View(); 
            } 
            [HttpPost] 
        public ActionResult add(CurdModel model) 
        { 
            if (model.id > 0) 
            { 
                SqlCommand command = new SqlCommand("UpdateRecordByIdSP", con); 
                command.CommandType = CommandType.StoredProcedure; 
                // add parameters    
                command.Parameters.Add("@Name", SqlDbType.VarChar).Value = model.name; 
                command.Parameters.Add("@Email", SqlDbType.VarChar).Value = model.email; 
                command.Parameters.Add("@Id", SqlDbType.Int).Value = model.id; 
                con.Open(); 
                int iRetVal = command.ExecuteNonQuery(); 
 
 
            } 
            else 
            { 
                SqlCommand command = new SqlCommand("AddNewRecordSP", con); 
                command.CommandType = CommandType.StoredProcedure; 
                // add parameters    
                command.Parameters.Add("@Name", SqlDbType.VarChar).Value = model.name; 
                command.Parameters.Add("@Email", SqlDbType.VarChar).Value = model.email; 
                command.Parameters.Add("@Id", SqlDbType.Int).Direction = ParameterDirection.Output; 
                con.Open(); 
                int iRetVal = command.ExecuteNonQuery(); 
                con.Close(); 
            } 
            return RedirectToAction("Index", "curd"); 
        } 
 
        public ActionResult Delete(int id) 
        { 
            SqlCommand command = new SqlCommand("DeleteRecordByIdSP", con); 
            command.CommandType = CommandType.StoredProcedure; 
            // add parameters   
 
            command.Parameters.Add("@Id", SqlDbType.Int).Value = id; 
            con.Open(); 
            command.ExecuteNonQuery(); 
            con.Close(); 
 
            return RedirectToAction("Index", "curd"); 
        } 
        public ActionResult Details(int id) 
        { 
            CurdModel mdl = new CurdModel(); 
            SqlCommand cmd = new SqlCommand("GetRecordByIdSP", con); 
            cmd.CommandType = CommandType.StoredProcedure; 
            cmd.Parameters.Add("@Id", SqlDbType.Int).Value = id; 
            SqlDataReader dr = null; 
            con.Open(); 
            dr = cmd.ExecuteReader(); 
 
            DataTable dt = new DataTable(); 
            dt.Load(dr); 
 
            mdl.id = Convert.ToInt32(dt.Rows[0][0].ToString()); 
            mdl.name = dt.Rows[0][1].ToString(); 
            mdl.email = dt.Rows[0][2].ToString(); 
 
            con.Close(); 
            return View(mdl); 
 
        } 
    } 

HostForLIFE.eu ASP.NET MVC 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 :: Using Ajax in MVC Application

clock June 21, 2016 00:16 by author Anthony

In asp.net web form application, if we need ajax service, we will need to create wcf services on server side to serve ajax calls, while in MVC web application, no wcf is needed, a controller will do.

Here are two examples (GET and POST) of how to use ajax in mvc application

Http Get example: ajax consumer in view

<script type="text/javascript">
  var user = {
                'id': 1
            };
    $.get(
                'home/getUser',
                user,
                function (data) {
                    alert(data.name);
                }
    );
</script>


Http Get example: ajax server in home controller

public class HomeController : Controller
{
    // data GET service
     public JsonResult getUser(int id)
     {
            User user = db.Users.where(u=>u.id==id)
            return Json(user,JsonRequestBehavior.AllowGet);     }
}

A few points:


Controller must return JsonResult rather than ActionResult as a normal controller does as we would want the data to be returnd as json data, and it does not have a ‘d’ wrapper

JsonRequestBehavior.AllowGet must be set in Json()call, otherwise you will get:

500 internal server error with message like

This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet

You only need to set this parameter for GET and returning JSON array to avoid JSON hijacking, no need for POST requests.
Http POST example: ajax consumer in view


<script type="text/javascript">
var user={
            'name':’TheUser’,
            'age':30
        };
 $.post(
            'home/SaveUser',
            user,
            function (data) {
                if (data === true) {
                   alert('User is saved');
                }
                else {

                    alert('Failed to save the user');
                }
            },
            'json'
        );
</script>


Http POST example: ajax server in home controller

public class HomeController : Controller
{
    // data POST service
  [AcceptVerbs(HttpVerbs.Post)]
   public JsonResult SaveUser (string name, int age)
   {
        return Json(true);    }
}

A few points:

Have to decorate the controller with ‘POST’

Datatype in $.post in example is set to json, but it is not necessary to be so, if you just pass data in fields rather than in complex object. When it is not set to json it will use application/x-www-form-urlencoded as a way to pass data in standard post.


Summary:
In asp.net MVC you can use controller as ajax server without having to use wcf, compared with wcf, no configuration is needed

 

HostForLIFE.eu ASP.NET MVC 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 :: Configuring ELMAH In ASP.NET MVC

clock June 13, 2016 21:35 by author Anthony

In this article, I will integrate and setup ELMAH to asp.net MVC project. I will finish whole article in 5 different steps. ELMAH stands for Error Logging Modules and Handlers providing application wide error logging facilities. ELMAH is pluggable and easy to implement without changing single line of code. ELMAH work as interceptor of unhandled dotnet exceptions, that display over yellow screen of death. As per Author you can dynamically add ELMAH on running asp.net application without recompile or re-deploy whole application.You can download ELMAH binaries from google code or if you are using nuget then visit ELMAH nuget page.

Install

The best way to install any module to Asp.net MVC project is to use Nuget package Console. You can visit ELMAH nuget page for get latest version command.

Configure

After installing ELMAH , it will automatically update Web.Config file. If it's not so you can add following code to Web.Config file.

<configuration>
<configSections>
    <sectionGroup name="elmah">
      <section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah" />
      <section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah" />
      <section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah" />
      <section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah" />
    </sectionGroup>
</configSections>

<system.web>   
    <httpModules>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" />
    </httpModules>
</system.web>

<system.webServer>
<modules>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler" />
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" preCondition="managedHandler" />
</modules>
</system.webServer>
<elmah>
    <security allowRemoteAccess="false" />
    <errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="YourConnectionStringName" />
</elmah>
    <location path="elmah.axd" inheritInChildApplications="false">
    <system.web>
      <httpHandlers>
        <add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
      </httpHandlers>
      <!--
      <authorization>
        <allow roles="admin" />
        <deny users="*" /> 
      </authorization>
      --> 
    </system.web>
    <system.webServer>
      <handlers>
        <add name="ELMAH" verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" preCondition="integratedMode" />
      </handlers>
    </system.webServer>
  </location>
</configuration>
Usage Now, It's time to use and test elmah for application. Generate exception in Home Controller
public ActionResult Index()
{
   throw new Exception("This is test Exception");
          
   return View();
}


after generating exception check your elmah like http://www.example.com/elmah.axd
Here is our output

integrate-elmah-in-aspnet-mvc

integrate elmah in asp. net mvc

Security

In addition ELMAH provides seamless security feature to prevent unauthorized access. Please read our next article to make your elmah secure.

Filtering

ELMAH identify and store exceptions in different category, you can make or edit ELMAH error screen with different filters which we will discuss in our next ELMAH series.

Notification

You can setup ELMAH email notification when any exception occurs. To unable notification option you must include below code

Add ErrorMail module
<httpModules>
    <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah"/>
</httpModules>


Add SMTP Setting
<system.net>
    <mailSettings>
        <smtp deliveryMethod="network">
            <network host="..." port="25" userName="..." password="..." />
        </smtp>
    </mailSettings>
</system.net>
 

or
<elmah>
<errorMail from="..." to="..."  async="true" smtpServer="..." smtpPort="25" userName="..." password="..." />
</elmah>

 

 


HostForLIFE.eu ASP.NET MVC 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 :: How To Make Simple Application In ASP.NET MVC Using Select2?

clock June 6, 2016 23:46 by author Anthony

In this tutorial, I will show you how to make simple application in ASP.NET MVC using Select2. The infinite scrolling feature has also been implemented with server side options population. Select2 is very useful for dropdown lists with large datasets.

Why Select2 :

  • Using this jQuery plugin for dropdown lists, you can implement features such as option grouping, searching, infinite scrolling, tagging, remote data sets and other highly used features.
  • To use select2 in web projects, you just have to include JavaScript and CSS files of Select2 in your website.
  • Current version of select2 is 4.0.0. You can easily include these files by installation of NuGet package ‘Select2.js’ from NuGet package manager.

Steps of Implementation:
1. Create a blank ASP.NET MVC project, and install NuGet packages Select2.js, jQuery and jQuery Unobtrusive.
2. Add one controller with the name ‘HomeController’ and add view for default method ‘Index’.
3. Create new class in Models folder ‘IndexViewModel.cs as shown below:

public class IndexViewModel
{
   [Required(ErrorMessage="Please select any option")]
   public string OptionId { get; set; }
}

4. Bind ‘Index.cshtml’ view with IndexViewModelClass as model, by adding the following line in Index view:

@model Select2InMvcProject.Models.IndexViewModel

5. In ‘Index.cshtml’, include the css and js files below:

<link href="~/Content/css/select2.css" rel="stylesheet" />
<script src="~/Scripts/jquery-2.1.4.js"></script>
<script src="~/Scripts/select2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>


6. Write the following code in the Index view for creation of select list:

@using (Html.BeginForm())
{
   <br /><br />
   @Html.DropDownListFor(n => n.OptionId, Enumerable.Empty<SelectListItem>(), new { @id = "txtOptionId", @style = "width:300px;" })
//Created selectlist with empty enumerable of SelectListItem and given //id as “txtOptionId”
   @Html.ValidationMessageFor(n => n.OptionId)
//Adds span of validation error message
   <br /><br />
<button type="submit">Submit</button>
   <br /><br />
}


7. For applying Select2 to the dropdown list created above, fetching data from server side and for infinite scroll, use the jQuery code below in Index view:

<script type="text/javascript">
   $(document).ready(function () {
       var pageSize = 20;
       var optionListUrl = '@Url.Action("GetOptionList", "Home")';
//Method which is to be called for populating options in dropdown //dynamically
       $('#txtOptionId').select2(
       {
           ajax: {
               delay: 150,
               url: optionListUrl,
               dataType: 'json',
               data: function (params) {
                   params.page = params.page || 1;
                   return {
                       searchTerm: params.term,
                       pageSize: pageSize,
                       pageNumber: params.page
                   };
               },
               processResults: function (data, params) {
                   params.page = params.page || 1;
                  return {
                       results: data.Results,
                       pagination: {
                           more: (params.page * pageSize) < data.Total
                       }
                   };
               }
           },
           placeholder: "-- Select --",
           minimumInputLength: 0,
           allowClear: true,
   });
});
</script>


8. Create new class in Models folder with name ‘Select2OptionModel’ and add the two classes below:

public class Select2OptionModel
{
       public string id { get; set; }
       public string text { get; set; }
}
public class Select2PagedResult
{
       public int Total { get; set; }
       public List<Select2OptionModel> Results { get; set; }
}


9. Create one new folder with name ‘Repository’ in the solution, and add new class in that folder with name ‘Select2Repository. The functions in this class are mentioned below:

public class Select2Repository
   {
       IQueryable<Select2OptionModel> AllOptionsList;
public Select2Repository()
{
           AllOptionsList = GetSelect2Options();
}
IQueryable<Select2OptionModel> GetSelect2Options()
                  {
                                     string cacheKey = "Select2Options";
                                     //check cache
                                     if (HttpContext.Current.Cache[cacheKey] != null)
                                     {
return (IQueryable<Select2OptionModel>)HttpContext.Current.Cache[cacheKey];
                                     }
                                     var optionList = new List<Select2OptionModel>();
                                     var optionText = "Option Number ";
                                     for (int i = 1; i < 1000; i++)
                                     {
                                     optionList.Add(new Select2OptionModel
                                     {
                                               id = i.ToString(),
                                               text = optionText + i
                                     });
                                   }
                                   var result = optionList.AsQueryable();
                                     //cache results
                                     HttpContext.Current.Cache[cacheKey] = result;
                                     return result;}
 
List<Select2OptionModel> GetPagedListOptions(string searchTerm, int pageSize, int pageNumber, out int totalSearchRecords)
                  {
                                     var allSearchedResults = GetAllSearchResults(searchTerm);
                                     totalSearchRecords = allSearchedResults.Count;
return allSearchedResults.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList();
                  }
                  List<Select2OptionModel> GetAllSearchResults(string searchTerm)
                  {

                                     var resultList = new List<Select2OptionModel>();
                                      if (!string.IsNullOrEmpty(searchTerm))
resultList = AllOptionsList.Where(n => n.text.ToLower().Contains(searchTerm.ToLower())).ToList();
                                     else
                                     resultList = AllOptionsList.ToList();
                                     return resultList;
                  }
                  public Select2PagedResult GetSelect2PagedResult(string searchTerm, int pageSize, int pageNumber)
                  {
                                     var select2pagedResult = new Select2PagedResult();
                                     var totalResults = 0;
                                     select2pagedResult.Results = GetPagedListOptions(searchTerm,
pageSize, pageNumber, out totalResults);
                                     select2pagedResult.Total = totalResults;
                                     return select2pagedResult;
}
}

10.  In HomeController class, create new method as shown below:

public JsonResult GetOptionList(string searchTerm, int pageSize, int pageNumber)
{
     var select2Repository = new Select2Repository();
     var result = select2Repository.GetSelect2PagedResult(searchTerm, pageSize, pageNumber);
     return Json(result, JsonRequestBehavior.AllowGet);
}

11. Once you are done with coding, you can build and run the project. The output will be shown as below:

dropdown1.png

dropdown2.png


HostForLIFE.eu ASP.NET MVC 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.

 



HostForLIFE.eu Proudly Launches ASP.NET Core 1.0 RC2 Hosting

clock June 4, 2016 01:07 by author Peter

HostForLIFE.eu was established to cater to an underserved market in the hosting industry; web hosting for customers who want excellent service. HostForLIFE.eu - a cheap, constant uptime, excellent customer service, quality, and also reliable hosting provider in advanced Windows and ASP.NET technology. HostForLIFE.eu proudly announces the availability of the ASP.NET Core 1.0 RC2 hosting in their entire servers environment.

ASP.NET is Microsoft's dynamic website technology, enabling developers to create data-driven websites using the .NET platform and the latest version is 5 with lots of awesome features. ASP.NET Core 1.0 RC2 is a lean .NET stack for building modern web apps. Microsoft built it from the ground up to provide an optimized development framework for apps that are either deployed to the cloud or run on-premises. It consists of modular components with minimal overhead.

A key change that occurred between RC1 and RC2 is the introduction of the .NET command-line interface.  This tool replaces the dnvm, dnx, and dnu utilities with a single tool that handles the responsibilities of these tools. In RC1 an ASP.NET application was a class library that contained a Startup.cs class. When the DNX toolchain run your application ASP.NET hosting libraries would find and execute the Startup.cs, booting your web application. Whilst the spirit of this way of running an ASP.NET Core application still exists in RC2, it is somewhat different. As of RC2 an ASP.NET Core application is a .NET Core Console application that calls into ASP.NET specific libraries. What this means for ASP.NET Core apps is that the code that used to live in the ASP.NET Hosting libraries and automatically run your startup.cs now lives inside a Program.cs.

HostForLIFE.eu hosts its servers in top class data centers that is located in Amsterdam (NL), London (UK), Paris (FR), Frankfurt(DE) and Seattle (US) to guarantee 99.9% network uptime. All data center feature redundancies in network connectivity, power, HVAC, security, and fire suppression. All hosting plans from HostForLIFE.eu include 24×7 support and 30 days money back guarantee. The customers can start hosting their ASP.NET Core 1.0 RC2 site on their environment from as just low €3.00/month only.

HostForLIFE.eu is a popular online ASP.NET based hosting service provider catering to those people who face such issues. The company has managed to build a strong client base in a very short period of time. It is known for offering ultra-fast, fully-managed and secured services in the competitive market.

HostForLIFE.eu offers the latest European ASP.NET Core 1.0 RC2 hosting installation to all their new and existing customers. The customers can simply deploy their ASP.NET Core 1.0 RC2 website via their world-class Control Panel or conventional FTP tool. HostForLIFE.eu is happy to be offering the most up to date Microsoft services and always had a great appreciation for the products that Microsoft offers.

Further information and the full range of features ASP.NET Core 1.0 RC2 Hosting can be viewed here http://hostforlife.eu



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How To Create Google Maps Sample App ASP.NET MVC And AngularJS

clock May 30, 2016 21:03 by author Anthony

Today I am going to explain how to create Google Maps Sample App with AngularJS and asp.net MVC. In one of the previous article, we have seen How to display google map in asp.net application andHow to load GMap Direction from database in ASP.NET using google map.

In order to use the Google Maps in our application, we need to add the following resources: 

  • angular.js
  • lodash.js - Loadash is a dependency of angular-google-maps library.
  • angular-google-maps.js - Angular Google Maps is a set of directives which integrate Google Maps in an AngularJS applications.

Just follow the following steps in order to create a sample google app with AngularJS and asp.net MVC:

Step - 1: Create New Project.

Go to File > New > Project > Select asp.net MVC4 web application > Entry Application Name > Click OK > Select Basic > Select view engine Razor > OK 

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add. Here I have added a database for store some location information in our database for show in the google map.  

Step-3: Create a table.

Here I will create 1 table (as below) for store location information. Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok. 

Step-4: Add Entity Data Model.

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-5: Create a Controller.

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add. Here I have created a controller "HomeController" 

Step-6: Add new action into the controller to get the view where we will show google map

Here I have added "Index" Action into "Home" Controller. Please write this following code 

public ActionResult Index()
{
    return View();
}

Step-7: Add another action (here "GetAllLocation") for fetch all the location from the database.

public JsonResult GetAllLocation()
{   
using (MyDatabaseEntities dc = new MyDatabaseEntities())   
{       
var v = dc.Locations.OrderBy(a => a.Title).ToList();      
return new JsonResult { Data = v, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}

Step-8: Add 1 more action (here "GetMarkerInfo") for getting google marker information from the database to show in the map.

public JsonResult GetMarkerInfo(int locationID)
{    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {        Location l = null;
        l = dc.Locations.Where(a => a.LocationID.Equals(locationID)).FirstOrDefault();
        return new JsonResult { Data = l, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}

Step-9: Add a new javascript file, will contain all the necessary logic to implement our Google Map.

Right Click on Action Method (here right click on Index action) > Add View... > Enter View Name > Select View Engine (Razor) > Add. 

var app = angular.module('myApp', ['uiGmapgoogle-maps']);
app.controller('mapController', function ($scope, $http) {
     //this is for default map focus when load first time
    $scope.map = { center: { latitude: 22.590406, longitude: 88.366034 }, zoom: 16 }
     $scope.markers = [];
    $scope.locations = [];
    //Populate all location
    $http.get('/home/GetAllLocation').then(function (data) {
        $scope.locations = data.data;
    }, function () {
        alert('Error');
    });
    //get marker info
    $scope.ShowLocation = function (locationID) {
        $http.get('/home/GetMarkerInfo', {
            params: {
                locationID: locationID
            }
        }).then(function (data) {
            //clear markers
            $scope.markers = [];
            $scope.markers.push({
                id: data.data.LocationID,
                coords: { latitude: data.data.Lat, longitude: data.data.Long },
                title: data.data.title,               
                address: data.data.Address,                               
                image : data.data.ImagePath           
});
            //set map focus to center
            $scope.map.center.latitude = data.data.Lat;
            $scope.map.center.longitude = data.data.Long;
        }, function () {
            alert('Error');
        });
    }
    //Show / Hide marker on map
    $scope.windowOptions = {
        show: true
    };
}); 

Step-10: Add view for the action (here "Index") & design.

Right Click on Action Method (here right click on Index action) > Add View... > Enter View Name > Select View Engine (Razor) > Add. HTML Code 

@{    ViewBag.Title = "Index";
}
<h2>Index</h2>
<div ng-app="myApp" ng-controller="mapController">
    <div class="locations">
        <ul>
            <li ng-repeat="l in locations" ng-click="ShowLocation(l.LocationID)">{{l.Title}}</li>
        </ul>
    </div>
    <div class="maps">
        <!-- Add directive code (gmap directive) for show map and markers-->
        <ui-gmap-google-map center="map.center" zoom="map.zoom">
            <ui-gmap-marker ng-repeat="marker in markers" coords="marker.coords" options="marker.options" events="marker.events" idkey="marker.id">
                <ui-gmap-window options="windowOptions" show="windowOptions.show">
                    <div style="max-width:200px">
                        <div class="header"><strong>{{marker.title}}</strong></div>
                        <div id="mapcontent">
                            <p>
                                <img ng-src="{{marker.image}}" style="width:200px; height:100px" />
                                <div>{{marker.address}}</div>
                            </p>
                        </div>
                    </div>
                </ui-gmap-window>
            </ui-gmap-marker>
        </ui-gmap-google-map>
    </div>
</div>
@* Now here we need to some css and js *@
<style>
    .angular-google-map-container {
        height:300px;
    }
    .angular-google-map {
        width:80%;
        height:100%;
        margin:auto 0px;
    }
    .locations {
        width: 200px;
        float: left;
    }
    .locations ul {
        padding: 0px;
        margin: 0px;
        margin-right: 20px;
    }
    .locations ul li {
        list-style-type: none;
        padding: 5px;
        border-bottom: 1px solid #f3f3f3;
        cursor: pointer;
    }
</style>
@section Scripts{
    @* AngularJS library *@
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.js"></script>
    @* google map directive js *@
    <script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>
    <script src="//rawgit.com/angular-ui/angular-google-maps/2.0.X/dist/angular-google-maps.js"></script>
    @* here We will add our created js file *@
    <script src="~/Scripts/ngMap.js"></script>
}

Step-11: Run Application.


HostForLIFE.eu ASP.NET MVC 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.

 



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