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 5 Hosting - HostForLIFE.eu :: How to Add a Video in ASP.NET MVC 5?

clock April 15, 2016 21:45 by author Anthony

In this tutorial, you’re going to learn how to add video using Entity Framework. We will be building a form for adding a new video to the database.Step 1: Creating a Page to Add a Video

Before we get started, let’s take a closer look at routing.

Earlier I told you that the routing engine determines the name of the controller and the action from the URL of the request. The default rule (or the default convention) targets a URL with the pattern /controller/action/id. Here both action and id are optional. If action is not specified, Index is assumed as the action name.

For the purpose of this section, we need a new page for the user to add a new video. To do this, we’re going to create a new action that responds to a URL like /videos/new. Inside this action, we’ll return a view which will include a data entry form for adding a video.

First, go to VideosController and create a new action like this:
public ActionResult New()
{
    return View();
}

All we do here is simply return a view. Let’s create the corresponding view. In Solution Explorer, expand the Views folder, right-click the Videos folder, and go to Add > View…. Set the name of the view to New and make sure _Layout.cshtml is selected as the layout (similar to the last section).

image09

Next, set the model behind this view on the top:

@model Beaver.Models.Video

We set the model to the Video because we’re going to capture a Video object in this form.
@using (Html.BeginForm("Add", "Videos", FormMethod.Post, new { @class = "form" }))
{

}



Here we are using Razor syntax (note the @) to write C# code. Html.BeginForm is a helper method, which we use to render an HTML form element. It returns an instance of MvcForm, which is a disposable object. By wrapping it inside a using block, we can ensure that it will be properly disposed.

The first and second arguments specify the name of the action and controller that will be called when we post this form. In this case, we expect an action named Add in our VideosController to be called. We haven’t created this action yet, but we’ll do so soon.

The third argument specifies the form method. In HTML forms, we have two methods: GET and POST. When sending data for modification to the server, we should always use the POST method.

The last argument is an anonymous object ( new {} ) that specifies any additional attributes to add to the HTML markup. So, when this code is executed, the view engine will render something like this:

<form action=”/videos/add” method=”post” class=”form”>
</form>

We use the form CSS class to give a nice, modern look to our forms. This CSS class is defined in Bootstrap, which is a CSS framework for building modern and responsive (mobile- and tablet-friendly) web applications. When you create an ASP.NET MVC project in Visual Studio, Bootstrap is automatically added for you.

We added the form. Now, we need to add three input fields in this form: Title, Description and Genre. Write this code inside the using block:Now, write the following code in the view to create an HTML form element:
 <div class="form-group">
        @Html.LabelFor(m => m.Title)
        @Html.TextBoxFor(m => m.Title, new { @class = "form-control" })
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Description)
        @Html.TextAreaFor(m => m.Description, new { @class = "form-control", rows = 4 })
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Genre)
        @Html.EnumDropDownListFor(m => m.Genre, new { @class = "form-control" })
    </div>

Here we have three sections, each wrapped with a div with a form-group class. Again, this is one of the classes that is defined in Bootstrap. If you follow Botostrap’s markup, you always get a nice, clean form that renders well both on the desktop and on mobile devices.

Inside each form-group, we have a label and an input field. Look at the first form-group.

<div class="form-group">
    @Html.LabelFor(m => m.Title)
    @Html.TextBoxFor(m => m.Title, new { @class = "form-control" })
</div>

We’re using Html.LabelFor to render a label for the Title property of the Video class.

@Html.LabelFor(m => m.Title)

The expression m => m.Title is a lambda expression that we use to access a property in the model of this view. If you’re not familiar with lambda expressions, check out my C# Advanced course on Udemy. When this line is executed by the view engine, we’ll get an HTML markup like this:

<label for=”Title”>Title</label>
Next, we use Html.TextBoxFor helper method to render a text box.

@Html.TextBoxFor(m => m.Title, new { @class = "form-control" })
Again, we use a lambda expression to specify the target property. Also, note that the second argument to this method is an anonymous object that specifies any additional attributes to add to the markup, in this case form-control CSS class. This is another Bootstrap class that gives our text boxes a bit of padding, round corners and a nice effect when the input is in focus. The result will be HTML markup like this:

<input type=”text” id=”Title” name=”Title” class=”form-control”></input>
Now you read the second form-group.

<div class="form-group">
        @Html.LabelFor(m => m.Description)
        @Html.TextAreaFor(m => m.Description, new { @class = "form-control", rows = 4 })
    </div>

It’s very similar to the first one, except that here we use the Html.TextAreaFor helper method to render a textarea input element instead of a text box. This allows the user to write a description that is more than one line.

And finally, in the third form-group, we use a different helper method (Html.EnumDropDownListFor) to render a drop-down list for the Genre property, which is an enum:

<div class="form-group">
        @Html.LabelFor(m => m.Genre)
        @Html.EnumDropDownListFor(m => m.Genre, new { @class = "form-control" })
    </div>

For the last step, we need a button to submit the form. Add this markup inside the using block, after all form groups:

<input type="submit" class="btn btn-primary" value="Save" />
Here, btn and btn-primary are both Bootstrap classes that make our buttons look cool and modern.

Your entire using block should look like this:

@using (Html.BeginForm("Add", "Videos", FormMethod.Post, new { @class = "form" }))
{
    <div class="form-group">
        @Html.LabelFor(m => m.Title)
        @Html.TextBoxFor(m => m.Title, new { @class = "form-control" })
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Description)
        @Html.TextAreaFor(m => m.Description, new { @class = "form-control", rows = 4 })
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Genre)
        @Html.EnumDropDownListFor(m => m.Genre, new { @class = "form-control" })
    </div>

    <input type="submit" class="btn btn-primary" value="Save" />
}

Now it’s time to review what we have done. Run the application with Ctrl+F5 and look at the form we’ve built:

Note how the input fields and the button look. This is all because of the beautiful styles defined in Bootstrap.
In this step, we added a new action to our controller that returned a view. We created a view with a form to add a video.

 


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



ASP.NET MVC 5 Hosting - HostForLIFE.eu :: ASP.NET MVC 5 Scaffolding

clock April 14, 2016 20:19 by author Anthony

ASP.NET Scaffolding is a code generation framework for ASP.NET Web applications. It makes it easy to add boilerplate code to your project that interacts with a data model.

In previous versions of Visual Studio, scaffolding was limited to ASP.NET MVC projects. With Visual Studio 2013, you can now use scaffolding for any ASP.NET project, including Web Forms. Visual Studio 2013 does not currently support generating pages for a Web Forms project, but you can still use scaffolding with Web Forms by adding MVC dependencies to the project. Support for generating pages for Web Forms will be added in a future update.

When using scaffolding, we ensure that all required dependencies are installed in the project. For example, if you start with an ASP.NET Web Forms project and then use scaffolding to add a Web API Controller, the required NuGet packages and references are added to your project automatically. To add MVC scaffolding to a Web Forms project, add a New Scaffolded Item and select MVC 5 Dependencies in the dialog window. There are two options for scaffolding MVC; Minimal and Full. If you select Minimal, only the NuGet packages and references for ASP.NET MVC are added to your project. If you select the Full option, the Minimal dependencies are added, as well as the required content files for an MVC project.

Support for scaffolding async controllers uses the new async features from Entity Framework 6.This Article shows how to use Scaffolding With your ASP.net MVC 5 Application.

Step 1 :

  • Let's create an ASP.net MVC 5 web application in Visual Studio 2013 and name it as ScaffoldingMVC5.

Scaffolding With ASP.net MVC 5

Step 2 :

  • Right click your Controllers folder and Add New Scaffolded Item is as below.

  • Scaffolding With ASP.net MVC 5


Step 3 :

  • From the Add Scaffold window, select the MVC 5 Controller with views,using Entity Framework scaffold template.

  • Scaffolding With ASP.net MVC 5

Step 4 :

  • The Add Controller window,you can give the name of your Controller (e.g. PetController),select your model class (e.g. Pet) and also you can create the Data context class (e.g. DataContext) as below. 
  • All other options are put as default.
  • After that click Add button.
  • When you click the New data context.. button  on Add Controller box above,it will pop up the below New Data Context box.
  • From there you can give a name for your Data context is as below.
  • e.g. DataContext

Scaffolding With ASP.net MVC 5


Step 5 :

  • The solution tree shows the relevant classes and pages were created for above example.
  • For example, the following image shows the MVC controller (i.e. PetController) and Views (i.e. Inside the Pet folder) that were created through scaffolding for a Model class named Pet.
  • Scaffolding With ASP.net MVC 5

 

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



ASP.NET MVC 5 Hosting - HostForLIFE.eu :: ASP.NET MVC 5 Custom Filter

clock April 1, 2016 21:37 by author Anthony

UNDERSTANDING ASP.NET MVC

ASP.NET MVC is the implementation of the MVC architecture to the programming framework. ASP.NET physically is library consisting of some assembly that can be installed on top .NET Framework 3.5. ASP.NET MVC was created as an option for developers who like MVC architecture. ASP.NET MVC did not replace Web Forms architecture that has been known and used by developers ASP.NET. The main components of ASP.NET MVC still the same as the basic architecture of MVC, the Model, View, and Controller. Some of the additional component is a web server, Routing, and dispatchers. Web server always bridging the interaction between the user with a web program. We can use the IIS web server, or a personal web server as long as the program is still in the development phase. IIS versions that can be used vary from version 5 to version 7.

ASP.NET MVC 5 Provides five different kinds of Filters. They are :

  • Authentication
  • Authorization
  • Action
  • Result
  • Exception

Filters are used to inject logic at the different levels of request processing. Let us understand where at the various stages of request processing different filters get applied. Authentication Authorization filter runs after the filter and before any other filter or action method. Action filter runs before and after any action method. Result filter runs before and after execution of any action result. Exception filter runs only if action methods, filters or action results throw an exception.

An action filter consists of codes that run either before or after an action runs. It can be used for tasks like logging, privileged based authorization, authentication, caching etc. Creating a custom action filter is very easy. It can be created in four simple steps:

  • Create a class
  • Inherit ActionFilterAttribute class
  • Override the OnActionExecuting method to run logic before the action method
  • Override the OnActionExecuted method to run logic after the action method

The purpose of the action filter is to find whether a logged in user belongs to a particular privileges or not. On the basis of the result, a user will access a particular action or navigate to the login action. To do this, I have created a class and extended the ActionFilterAttribute class.

using PrivilegeDemo.Services;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using System.Web.Routing;
 
namespace PrivilegeDemo.Filters
{
    public class AuthorizationPrivilegeFilter : ActionFilterAttribute
    {
      
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
         
            AuthorizationService _authorizeService = new AuthorizationService();
            string userId = HttpContext.Current.User.Identity.GetUserId();
            if (userId != null)
            {
                var result = _authorizeService.CanManageUser(userId);
                if (!result)
                {
 
                    filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary{{ "controller", "Account" },
                                          { "action", "Login" }
 
                                         });
                }
            }
            else
            {
                filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary{{ "controller", "Account" },
                                          { "action", "Login" }
 
                                         });
 
            }
            base.OnActionExecuting(filterContext);
        }
 
 
    }
}

 

The OnActionExecuting method is overridden because we want the code to execute before the action method gets executed. Once the action filter is created, it can be used in three ways:

  • As Global filter
  • As Controller
  • As Action

By adding a filter to the global filter in App_Start\FilterConfig it will be available globally to the entire application.

public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
           filters.Add(new AuthorizationPrivilegeFilter());
        }
    }

By adding a filter to a particular Controller it will also be available to the all actions of that particular controller.

[AuthorizationPrivilegeFilter]
    public class HomeController : Controller
    {

Adding a filter to a particular action it will be available to the particular action.

[AuthorizationPrivilegeFilter]
        public ActionResult About()
        {

 

 

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



ASP.NET MVC 5 Hosting - HostForLIFE.eu :: How to Make ASP.NET MVC 5 Run in Ubuntu?

clock March 31, 2016 18:04 by author Anthony

ASP.NET is a programming framework to create web application server side. ASP.NET using C # code is well structured so it is easy to understand and repair. C # also provides a variety of code hint, hint error before the code is executed. C # is executed using JIT system, so it may be able to run faster than interpreted languages like PHP.

But until a few years ago ASP.NET can only run on windows platform. Because there are some who still is Microsoft's patents, these projects difficult to run optimally and tend to be limited compatibility, even dotGNU project to a halt in 2012. So today I will discuss about how to run ASP.NET MVC 5 on Ubuntu Linux.

Before that some things need to be prepared, such as:

  • Computers with 14:04 LTS Ubuntu operating system.
  • ASP.NET MVC 5 that has been published.
  • Internet connection.

How to Make ASP.NET MVC 5 Run in Ubuntu?

  • Make sure that your operating system has been updated by running the following command:
    sudo apt-get update && sudo apt-get dist-upgrade
  • Install apache2 package by running the command:
    sudo apt-get install apache2
  • Input Mono into the system package list, this needs to be done so that the mono version that will be installed up to date. make sure you run the code below line by line.
    sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
    sudo echo "deb http://download.mono-project.com/repo/debian wheezy main" | sudo tee /etc/apt/sources.list.d/mono-xamarin.list
    sudo echo "deb http://download.mono-project.com/repo/debian wheezy-apache24-compat main" | sudo tee -a /etc/apt/sources.list.d/mono-xamarin.list
    sudo echo "deb http://download.mono-project.com/repo/debian alpha main" | sudo tee /etc/apt/sources.list.d/mono-xamarin-alpha.list
    sudo apt-get update && sudo apt-get dist-upgrade
  • Install mono-complete package
    sudo apt-get install mono-complete
  • Install libapache2-mod-mono package
    sudo apt-get install libapache2-mod-mono
    sudo a2enmod mod_mono_auto
  • Set apache2, so that the apache2 folder using mono. This procedure must be repeated for each new application
    sudo nano /etc/apache2/sites-available/testasp.conf
  • Copy-paste the following lines into the console, adjust the path and name if necessary. click ctrl + o, enter the ctrl + x to save the file.
    Alias /testasp "/var/www/html/testasp"
    MonoServerPath inventory "/usr/bin/mod-mono-server4"
    MonoDebug inventory true
    MonoSetEnv inventory MONO_IOMAP=all
    MonoApplications inventory "/testasp:/var/www/html/testasp"
    <Location "/testasp">
    Allow from all
    Order allow,deny
    MonoSetServerAlias inventory
    SetHandler mono
    SetOutputFilter DEFLATE
    SetEnvIfNoCase Request_URI "\.(?:gif|jpe?g|png)$" no-gzip dont-vary
    </Location>
    <IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/javascript
    </IfModule>

  • Create a new folder in the / var / www / html / testasp, adjust permissions folder if necessary. Asp.net files will be stored here.
    sudo mkdir /var/www/html/testasp
  • Enable configuration site that have been created.
    sudo a2ensite testasp
    sudo service apache2 restart
  • Upload or copy the files you want to run ASP.NET MVC into the folder / var / www / html / testasp.
  • Test sites in the browser, adjust your url with IP engine.
  • Done. You have been successfully run ASP.NET MVC 5 on the Linux operating system.

 

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



ASP.NET MVC 5 Hosting - HostForLIFE.eu :: How to Create ASP.NET MVC 5 Page

clock March 29, 2016 18:31 by author Anthony

Here we will give an example of how to create ASP.NET MVC 5 page with examples, they can be seen on ASP.NET MVC framework to be displayed on the web browser. We are going on to describe some things about the basics of ASP.NET MVC that should be known.

You need to know what is included on the MVC Pattern Architectural Pattern. And software design pattern that is used in ASP.NET MVC is Front Controller, which means that the control will be concentrated in a class alone. While ASP.NET Web Forms is different because it has a controller on each page.

Here's how the MVC, can be seen in the following figure

 

In ASP.NET MVC 5, the address will be written in the address bar on your web browser does not show as physical files, because of the configuration and routing processes that can be seen in Global.asax.cs and RouteConfig.cs file (folder App_start).

Global.asax file can also be found on the project ASP.NET Web Forms, this file serves as an application file that is responsible for the events at the application level is raised by ASP.NET or HttpModules. At the time the application is run, namely on Application_Start method, can be seen there are file event handling. Then it can be seen on these methods belong to the class RouteConfig. Here is the content of the class RouteConfig residing on file in the folder App_Start RouteConfig.cs.

It can be seen that the name of the default controller is used in this application is Home. This means that if you follow the code needs to be created with the name of the Home controller class, and then save it in a folder Controllers.

To add this class please right click on the folder and select Add Controller > Controller

Select the MVC Controller 5 - Empty and then click the Add button.

It will display a window Add Controller that serves to give the name of the controller class that will be created. For example, assign a name to the Home Controller Controller name column, then click the Add button.

Here is the content of the class controller of HomeController that have been made :

Then make special view for HomeController class in Home folder with index.cshtml. Then right click on the Home folder, then choose Add > New Item. After that, Choose MVC 5 View Page, give a name as you desire, click Add button.

Then you can modify Index.cshtml file like this :

You can try it on your web browser, then this will be the result

HostForLIFE.eu ASP.NET MVC 5 Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Implement RoleManager in ASP.NET MVC 5?

clock December 11, 2015 00:34 by author Peter

There is something great included in ASP.NET MVC 5 that looks underutilized except by the ASP.NET MVC team. the rest of us seem to be ignoring it, that is apparent when gazing the solutions on StackOverflow (and blogs) for questions like “how do i use roles with ASP.NET MVC 5?” once I check out how identity is implemented in mvc, what stands out is that the dependency injection. And, that dependency injection seems to be missing in the answers to how to implement roles. Dependency is a great tool, it’s built into the OWIN implementation, so why not use it?

To implement the role manager in MVC 5, look for a file in App_Start called IdentityConfig.cs. If you don’t have this file, look for the file that contains the implementation of your ApplicationUserManager (derived from UserManager) and ApplicationSignInManager (derived from SignInManager). At the bottom of that file, within the namespace, add the subsequent class definition:
public class ApplicationRoleManager : RoleManager<IdentityRole>
{
public ApplicationRoleManager(IRoleStore<IdentityRole, string> store) : base(store)
{
}

public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
{
    var roleStore = new RoleStore<IdentityRole>(context.Get<AuthenticationDbContext>());
    return new ApplicationRoleManager(roleStore);
}
}


There are a couple of prototypes for the produce method. during this case, I needed to urge the database context from the OWIN context, so I used the more elaborate overload. If you don’t want to do that, you can use the Create(Func&lt;T&gt;) overload, which doesn’t take any parameters.  Now, to make sure OWIN knows about your ApplicationRoleManager class, go the ConfigureAuth method in your Startup partial class implementation in Startup.Auth.cs (also in App_Start).  Or, you'll also put what I’m getting ready to show you in the Configuration method of the OWIN startup class. This class is sometimes called Startup.cs and you’ll find it in the same directory as the root web.config.
public void ConfigureAuth(IAppBuilder app)
{
   // Configure the db context, user manager and signin manager to use a single instance per request
   app.CreatePerOwinContext(AuthenticationDbContext.Create);
   app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
   app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
   app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
   …
}

See how I just stuck that line for ApplicationRoleManager there next to the other authentication delegate registrations?  Now, we can just inject the role manager right into the AccountController or whatever other controller we need.
public AccountController(
    SendMailManager emailManager,
    ApplicationUserManager userManager,
    ApplicationSignInManager signInManager,
    ApplicationRoleManager roleManager)
{
    this.MailManager = emailManager;
    this.RoleManager = roleManager;
    this.SignInManager = signInManager;
    this.UserManager = userManager;
}

As you can see, I have already used the dependency injection to insert my own mail manager. AccountController should already be set up with this kind of structure. If it’s not, though, simply changing your constructor to look like this will cause MVC to inject those dependencies into your controller. Then, all you have to do is create a property to hold that ApplicationRoleManager thing and you’re all set!
private ApplicationRoleManager roleManager;
public ApplicationRoleManager RoleManager
{
    get
    {
        return this.roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
    }
    private set { this.roleManager = value; }
}

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.



Free ASP.NET MVC 5 Hosting - HostForLIFE.eu :: How to Create Web Application with ASP.NET MVC 5

clock June 5, 2015 06:04 by author Rebecca

This post will show you how to create a new ASP.NET MVC 5 application using Visual Studio 2013.

Step 1

Open Visual Studio 2013. It goes without saying, you're gonna need Visual Studio to create a web application using ASP.NET, and the version you will need for ASP.NET MVC 5 is Visual Studio 2013.

Step 2

Create a new ASP.NET MVC 5 Application:

  • Click File, New, then Project.

  • Select Web, then ASP.NET Web Application, give the project a name, and then click OK.

  • Select the MVC template, tick Add unit tests, and then click OK.

Step 3

Update existing NuGet packages. Click on Tools, then NuGet Package Manager, then NuGet Package Manager Console.

Then, enter the following command into the Package Manager Console window:

Update-Package

This will update all the existing packages.

Step 4

Run your new web application for the first time. Click on the MyWebApplication project, and then click the Play icon to launch the website.

Step 5

Admire your new project!

That's it!

A newly created web application that includes some impressive functionality out of the box. The default template gives you:

  • Bundling and minification.
  • The ability to register, and sign into your account.
  • A snazzy prebuilt layout that uses bootstrap.
  • And you get a framework that lets you create scaleable web applications using the well-established MVC design pattern.

Free ASP.NET MVC Hosting
Try our Free ASP.NET MVC Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc.



ASP.NET MVC 5 Hosting France - HostForLIFE.eu :: Using Fluent Validation in ASP.NET MVC 5

clock April 10, 2015 06:22 by author Rebecca

In this article, i help you to learn how to use Fluent Validation in ASP.NET MVC 5 implementation. Fluent validation is one way to set up dedicated validator objects, that you would use when you want to separate validation logic from business logic. Fluent validation contains a small validation library for .NET that uses a Fluent interface and lambda expressions for building validation rules for our business objects.

So, let's start using Fluent Validation!

Step 1:  Create a ASP.NET Application using MVC Template

First, click on "Tools" , choose "Library Package Manager" then "Package Manager Console" and type this following command:

install-package FluentValidation

Step 2: Lets create a Model class with the properties

namespace samplefluentvalidation.Models
{
    public class Products
    {
        public int ProductID { get; set; }
        public string ProductName { get; set; }
        public string ProductManufacturer { get; set; }
    }
}

Step 3:  Now lets Create a controller

using FluentValidation.Results;
using samplefluentvalidation.Models;
using samplefluentvalidation.Models.Validations;
using System.Web.Mvc;

namespace samplefluentvalidation.Controllers
{
    public class ProductsController : Controller
    {
        //
        // GET: /Products/
        public ActionResult Index()
        {
            return View();
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(Products model)
        {
            ProductValidator validator = new ProductValidator();
            ValidationResult result = validator.Validate(model);
            if (result.IsValid)
            {
                ViewBag.ProductName = model.ProductName;
                ViewBag.ProductManufacturer = model.ProductManufacturer;
              
            }
            else
            {
                foreach (ValidationFailure failer in result.Errors)
                {
                    ModelState.AddModelError(failer.PropertyName, failer.ErrorMessage);
                }
            }
            return View(model);
        }
    }
}

Step 4:  Now create a folder named products in views

Add a view named Index and add the below lines:

@model samplefluentvalidation.Models.Products
@{
    ViewBag.Title = "Index";
}
@if (ViewData.ModelState.IsValid)
{
    <b>
       Product Name : @ViewBag.ProductName<br />
       Product Manufacturer : @ViewBag.ProductManufacturer
    </b>
}
@using (Html.BeginForm())
{
    <fieldset>
        <legend>Products</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.ProductName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ProductName)
            @Html.ValidationMessageFor(model => model.ProductName)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.ProductManufacturer)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ProductManufacturer)
            @Html.ValidationMessageFor(model => model.ProductManufacturer)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Now, we have created all the model controller. This view shows the index page and the validation check.

HostForLIFE.eu ASP.NET MVC 5.0 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 5 Hosting - HostForLIFE.eu :: How to Use Ninject in ASP.NET MVC 5 and WEB API 2

clock April 6, 2015 11:57 by author Rebecca

Dependency injection frameworks are becoming a common place in all modern code bases. One of the most popular dependency injection framework in the .NET world is Ninject. This post will show a very simple example of how you can get started with Ninject.

Step 1:
Create any empty ASP.NET web application and choose the WEB API template.

Step 2:
Create a folder called Services where you will put your business logic classes.

Step 3:
Lets create a simple service called TaxService.cs like below:

namespace Ninjectsample.Services 
{
    public class TaxService : ITaxService
    {
        public double GetTaxRate()
        {
            return 0.7;
        }
    }

}
namespace Ninjectsample.Services 
{
    public interface ITaxService
    {
        double GetTaxRate();
    }
}

Step 4:
If we want to pass business logic into the HomeController, we can do it like this:

using Ninjectsample.Services; 
using System.Web.Mvc; 
namespace Ninjectsample.Controllers 
{
    public class HomeController : Controller
    {
        ITaxService _taxService;
        public HomeController(ITaxService taxService)
        {
            _taxService = taxService;
        }

        public ActionResult Index()
        {
            var rate = _taxService.GetTaxRate();

            return View(rate);
        }
    }
}

Then, I modified Index.cshtml to be simple like:
@model double
@Model

Step 5:
At this point if you run it, ASP.NET will complain because no one is giving the controller an instance of ITaxService. That's where you can use dependency injection frameworks like Ninject. You can install Nuget package called Ninject.MVC3. Don't worry, it will work even on MVC5!

Now, in the App_Start folder you will have a new file called NinjectWebCommon.cs.

Then, find and modify the RegisterServices method like below, don't forget to include your namespaces:
private static void RegisterServices(IKernel kernel) 
{
    kernel.Bind<ITaxService>().To<TaxService>();
}
Now, when you go to /Home/Index you will see the tax rate.

Step 6:
Similarly, you also inject business logic into a WEB API controller like below:

using Ninjectsample.Services; 
using System.Web.Http; 
namespace Ninjectsample.Controllers 
{
    public class ValuesController : ApiController
    {
        ITaxService _taxService;
        public ValuesController(ITaxService taxService)
        {
            _taxService = taxService;
        }

        public string Get()
        {
            return _taxService.GetTaxRate().ToString();
        }
    }
}

However, you need to install a Nuget package called Ninject.Web.WebApi.

Now, when you access /api/values you will see the desired result.

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