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.



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.


Tag cloud

Sign in