European ASP.NET MVC 4 and MVC 5 Hosting

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

ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Persistant Cookies in ASP.NET MVC 6

clock December 1, 2016 08:05 by author Peter

As with the most things in ASP.NET MVC 6, just about everything is handled within your Startup.cs file. With this tutorial, you will set up all your necessary routing, services, dependency injection, and more. And setting an expiration for a persistent cookie, turns out to be no different.
 

To set your persistent cookie expiration, you will need to associate the cookie to your current Identity provider. This is handled within the ConfigureServices method of the previously mentioned Startup.cs file, as you can see on the following code:
    public void ConfigureServices(IServiceCollection services)   
    { 
                // Add Entity Framework services to the services container along 
                // with the necessary data contexts for the application 
                services.AddEntityFramework() 
                        .AddSqlServer() 
                        .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration["Data:IdentityConnection:ConnectionString"])) 
                        .AddDbContext<YourOtherContext>(options => options.UseSqlServer(Configuration["Data:DataConnection:ConnectionString"])); 
     
                // Add Identity services to the services container 
                services.AddIdentity<ApplicationUser, IdentityRole>(i => { 
                            i.SecurityStampValidationInterval = TimeSpan.FromDays(7); 
                        }) 
                        .AddEntityFrameworkStores<ApplicationDbContext>()                    
                        .AddDefaultTokenProviders(); 
     
                // Other stuff omitted for brevity 
    } 


You might have noticed after a quick peek at this code what exactly you need to be setting. That's right. The SecurityStampValidationInterval property:
    // This will allow you to set the duration / expiration of your 
    // authentication token 
    i.SecurityStampValidationInterval = TimeSpan.FromDays(7); 


This example would only require the users to re-validate if they have not logged into the application within seven days. You can simply adjust this interval value to suit your needs.

 

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 :: Using Filters and Attribute Class In ASP.NET MVC

clock November 22, 2016 07:26 by author Peter

In this post, I will explain you about using filters and attribute class in ASP.NET MVC. ASP.NET MVC provides an easy way to inject your piece of code or logic either before or after an action is executed. this will be achieved by using filters and attribute classes.

Types of Filters
The ASP.NET MVC framework provides five types of filters and executes in the same order as given below,

    Authentication filters
    Authorization filters
    Action filters
    Result filters
    Exception filters

Build an action method in HomeController and declare Attribute classes Above Action Method.
    public class HomeController: Controller 
     
    { 
        [CustomAuthorizationAttribute] 
        [CustomActionAttribute] 
        [CustomResultAttribute] 
        [CustomExceptionAttribute] 
     
        public ActionResult Index()  
        { 
     
            ViewBag.Message = "Index Action of Home controller is being called."; 
            return View(); 
        } 
    } 

Now, build a Filters Folder in your application and add the following attribute classes.

    CustomAuthorizationAttribute.cs
        public class CustomAuthorizationAttribute: FilterAttribute, IAuthorizationFilter 
         
        { 
            void IAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext)  
            { 
                filterContext.Controller.ViewBag.OnAuthorization = "IAuthorizationFilter.OnAuthorization filter called"; 
            } 
        } 
    CustomActionAttribute.cs
        public class CustomActionAttribute: FilterAttribute, IActionFilter  
        { 
            void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)  
            { 
                filterContext.Controller.ViewBag.OnActionExecuting = "IActionFilter.OnActionExecuting filter called"; 
            } 
            void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)  
            { 
                filterContext.Controller.ViewBag.OnActionExecuted = "IActionFilter.OnActionExecuted filter called"; 
            } 
        }
    CustomResultAttribute.cs
        public class CustomResultAttribute: FilterAttribute, IResultFilter 
        { 
            void IResultFilter.OnResultExecuting(ResultExecutingContext filterContext)  
            { 
                filterContext.Controller.ViewBag.OnResultExecuting = "IResultFilter.OnResultExecuting filter called"; 
            } 
            void IResultFilter.OnResultExecuted(ResultExecutedContext filterContext)  
            { 
                filterContext.Controller.ViewBag.OnResultExecuted = "IResultFilter.OnResultExecuted filter called"; 
            } 
        } 
    CustomExceptionAttribute.cs
        public class CustomExceptionAttribute: FilterAttribute, IExceptionFilter  
        { 
            void IExceptionFilter.OnException(ExceptionContext filterContext)  
            { 
                filterContext.Controller.ViewBag.OnException = "IExceptionFilter.OnException filter called"; 
            } 
        } 


View
Index.cshtml
    @{ 
    ViewBag.Title = "Index"; 
    } 
    <h2> 
    Index</h2> 
    <ul> 
    <li>@ViewBag.OnAuthorization</li> 
    <li>@ViewBag.OnActionExecuting</li> 
    <li>@ViewBag.OnActionExecuted</li> 
    <li>@ViewBag.OnResultExecuting</li> 
    <li>@ViewBag.OnResultExecuted</li> 
    <li>@ViewBag.Message</li> 
    </ul> 


The following image is the output:

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 :: 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.

 



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