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

Free ASP.NET MVC 6 Hosting UK – HostForLIFE.eu :: How to Creating Routes with ASP.NET MVC 6

clock April 29, 2015 08:01 by author Peter

In this tutorial, I will show you how to create routes with ASP.NET MVC 6. When using MVC 6, you don’t create your Route collection yourself.

You let MVC create the route collection for you. And now, write the following code:
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
namespace RoutePlay
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }
        public void Configure(IApplicationBuilder app)
        {
            app.UseMvc();
        }
    }
}

The ConfigureServices() method is utilized to enroll MVC with the Dependency Injection framework built into ASP.NET 5. The Configure() system is utilized to register MVC with OWIN. This is what my MVC 6 ProductsController resembles:

Notice that I have not configured any routes. I have not utilized either tradition based or property based directing, yet I don't have to do this. If I enter the request “/products/index” into my browser address bar then I get the response “It Works!”:

When you calling the ApplicationBuilder.UseMvc() in the Startup class, the MVC framework will add routes for you automatically. The following code will show you, what the framework code for the UseMvc() method looks like:
public static IApplicationBuilder UseMvc([NotNull] this IApplicationBuilder app)
{
    return app.UseMvc(routes =>
    {
    });
}
public static IApplicationBuilder UseMvc(
    [NotNull] this IApplicationBuilder app,
    [NotNull] Action<IRouteBuilder> configureRoutes)
{
    // Verify if AddMvc was done before calling UseMvc
    // We use the MvcMarkerService to make sure if all the services were added.    MvcServicesHelper.ThrowIfMvcNotRegistered(app.ApplicationServices);
    var routes = new RouteBuilder
   {
        DefaultHandler = new MvcRouteHandler(),
        ServiceProvider = app.ApplicationServices
    };
     configureRoutes(routes);
     // Adding the attribute route comes after running the user-code because
    // we want to respect any changes to the DefaultHandler.
    routes.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(
        routes.DefaultHandler,
        app.ApplicationServices));
     return app.UseRouter(routes.Build());
}


The AttributeRouting.CreateAttributeMegaRoute() does all of the heavy-lifting here (the word “Mega” in its name is very appropriate). The CreateAttributeMegaRoute() method iterates through all of your MVC controller actions and builds routes for you automatically.
Now, you can use convention-based routing with ASP.NET MVC 6 by defining the routes in your project’s Startup class. And here is the example code:
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Routing;
using Microsoft.Framework.DependencyInjection;
namespace RoutePlay
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }
       public void Configure(IApplicationBuilder app)
        {
            app.UseMvc(routes =>
            {
                // route1
                routes.MapRoute(
                    name: "route1",
                    template: "super",
                    defaults: new { controller = "Products", action = "Index" }
                );
                // route2
                routes.MapRoute(
                    name: "route2",
                    template: "awesome",
                    defaults: new { controller = "Products", action = "Index" }
                );
            });
        }
    }
}


I hope this tutorial works for you!

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. You will not be charged a cent for trying our service for the next 3 days. Once your trial period is complete, you decide whether you'd like to continue.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Produce Output in ASP.NET MVC using Different Action Methods (View Action Method)

clock April 24, 2015 06:40 by author Rebecca

Action methods are the obvious way to produce output to the web page from controller in ASP.NET MVC. It can be a complete web page, a string or an object. Start from today until the next few days, we're going to learn different ways to produce output to the web page using action methods in ASP.NET MVC. Each action method returns different types of action results, however, most of action results derives from "ActionResult" class so returning "ActionResult" from these controller method would suffice your need.

In this part, I will show you how to use View Action Methods that are available to produce an output in ASP.NET MVC.

View() Action Method

View() action method is used to render a view as a web page. In this case, View will be the .cshtml page available in the View folder with the name of the method from which this is being called.

    public ViewResult OutputView()
            {
                return View();
            }


The above View() method will render OutputView.cshtml (the location of this View depends on under which controller this method is written) from Views folder to the browser. View() method returns ViewResult action type that derives from ActionResult class.

View(Model) Action Method

View() method when passed with an object as a parameter returns the View as a web page, with the object (model) being passed so that View can use this model to render data.

    public ViewResult OutputViewWithModel(UserNamePasswordModel model)

            {
  return View(model); // returns view with model

            }    The above method will render OutputViewWithModel.cshtml from Views folder to the browser.
The View must have @model directive in order to retrieve data from Model.

    @model Restaurant.Models.UserNamePasswordModel

    @{

        ViewBag.Title = Model.UserName;
     }

View("ViewName") Action method

View() method when passed with the View name renders the view that is passed as parameter as a web page.

    public ViewResult OutputViewWithModel(UserNamePasswordModel model)
            {
                return View("OutputView"); // returns the view that is passed as paramter
            }

The above code will render "OutputView" view to the page. Please note that View name should not contain the extension name (.cshtml) of the view.

That's the way to produce output in ASP.NET MVC using View Action Method. Just look forward to further discussion in the next article.

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 Hosting - HostForLIFE.eu :: Creating a Custom Remote Attribute and Override IsValid() Method

clock April 20, 2015 06:12 by author Rebecca

Today, I'm gonna tell you how to create a costum remote attribute and override IsValid() Method. In addition, remote attribute only works when JavaScript is enabled. If you disables JavaScript on your machine then the validation does not work. This is because RemoteAttribute requires JavaScript to make an asynchronous AJAX call to the server side validation method. As a result, you will be able to submit the form, bypassing the validation in place. This why it is always important to have server side validation.

To make server side validation work, when JavaScript is disabled, there are 2 ways:

  1. Add model validation error dynamically in the controller action method.
  2. Create a custom remote attribute and override IsValid() method.

How to Create a Costum Remote Attribute

Step 1:

Right click on the project name in solution explorer and a folder with name = "Common"

Step 2:

Right click on the "Common" folder, you have just added and add a class file with name = RemoteClientServer.cs

Step 3:

Copy and paste the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.Reflection;

namespace MVCDemo.Common
{
    public class RemoteClientServerAttribute : RemoteAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            // Get the controller using reflection
            Type controller = Assembly.GetExecutingAssembly().GetTypes()
                .FirstOrDefault(type => type.Name.ToLower() == string.Format("{0}Controller",
                    this.RouteData["controller"].ToString()).ToLower());
            if (controller != null)
            {
                // Get the action method that has validation logic
                MethodInfo action = controller.GetMethods()
                    .FirstOrDefault(method => method.Name.ToLower() ==
                        this.RouteData["action"].ToString().ToLower());
                if (action != null)
                {
                    // Create an instance of the controller class
                    object instance = Activator.CreateInstance(controller);
                    // Invoke the action method that has validation logic
                    object response = action.Invoke(instance, new object[] { value });
                    if (response is JsonResult)
                    {
                        object jsonData = ((JsonResult)response).Data;
                        if (jsonData is bool)
                        {
                            return (bool)jsonData ? ValidationResult.Success :
                                new ValidationResult(this.ErrorMessage);
                        }
                    }
                }
            }

            return ValidationResult.Success;
            // If you want the validation to fail, create an instance of ValidationResult
            // return new ValidationResult(base.ErrorMessageString);
        }

        public RemoteClientServerAttribute(string routeName)
            : base(routeName)
        {
        }

        public RemoteClientServerAttribute(string action, string controller)
            : base(action, controller)
        {
        }

        public RemoteClientServerAttribute(string action, string controller,
            string areaName) : base(action, controller, areaName)
        {
        }
    }
}

Step 4:

Open "User.cs" file, that is present in "Models" folder. Decorate "UserName" property with RemoteClientServerAttribute.

RemoteClientServerAttribute is in MVCDemo.Common namespace, so please make sure you have a using statement for this namespace.
public class UserMetadata
{
    [RemoteClientServer("IsUserNameAvailable", "Home",
        ErrorMessage="UserName already in use")]
    public string UserName { get; set; }
}

Disable JavaScript in the browser, and test your application. Notice that, we don't get client side validation, but when you submit the form, server side validation still prevents the user from submitting the form, if there are validation errors.

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. You will not be charged a cent for trying our service for the next 3 days. Once your trial period is complete, you decide whether you'd like to continue.



Free ASP.NET MVC Hosting - HostForLIFE.eu :: Processing Form Data using MVC Pattern

clock April 17, 2015 05:57 by author Rebecca

In this post, I will show you how to send form data to controller class using MVC pattern. Here, we will create simple HTML form and will send data to controller class, and then we will display same data in another view.

Step 1: Create Model Class

At first, we will create one simple model class called “Person” for this example.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MVC3.Models
{
    public class Person
    {
        public String Name{ get; set; }
        public StringSurname { get; set;
    }
    }
}

Step 2: Create simple HTML Form to Take Input

It’s view in MVC architecture. We will create two textboxes and one submit button in this view.
<%@ Page
Language="C#"
Inherits="System.Web.Mvc.ViewPage<dynamic>"
%>
<!DOCTYPE html>
<html>
<head runat="server">
    <title>PersonView</title>
</head>
<body>
    <div>
    <form method="post" action="Person/SetPerson">
        Enter Name:- <input type="text" id="Name" name="Name" /> <br />
        Entersurname:- <input type="text" id="surname" name="surname" />
        <input type="submit" value="Submit" />
    </form>
    </div>
</body>
</html>

Step 3: Create simple Controller to Invoke the View.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC3.Models;
namespace MVC3.Controllers
{
    public class PersonController : Controller
    {
        //
        // GET: /Person/
        public ActionResult ShowForm()
        {
            return View("PersonView");
        }
        [HttpPost]
        public ActionResult SetPerson()
        {
            String Name = Convert.ToString(Request["Name"]);
            String Surname = Convert.ToString(Request["surname"]);
            Person p = new Person();
            p.Name = Name;
            p.Surname = Surname;
            ViewData["Person"] = p;
            return View("ShowPerson");
        }
 
    }
}

In this controller, we are seeing two actions the ShowForm() action is the default action for Person Controller and SetPerson() action will call another view to display data. We can see within SetPerson() action,we are creating object of controller class and assigning value to it. At last we are assigning populated object to ViewData. Then we are calling one view called “ShowPerson”. This view will display data.

Create showPerson view

<%@ Page
Language="C#"
Inherits="System.Web.Mvc.ViewPage<dynamic>"
%>
<!DOCTYPE html>
<html>
<head runat="server">
    <title>ShowPerson</title>
</head>
<body>
    <div>
    <% var P = (MVC3.Models.Person)ViewData["Person"];%>      
       Person Name is :- <%= P.Name %> <br />      
       Person Surname is :- <%= P.Surname %>
    </div>
</body>
</html>

Here is the sample output:

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. You will not be charged a cent for trying our service for the next 3 days. Once your trial period is complete, you decide whether you'd like to continue.



Free ASP.NET MVC Hosting - HostForLIFE.eu :: HTML Helper For Image (@Html.Image): Developing Extension in MVC

clock April 16, 2015 08:42 by author Peter

Today I worked on a project wherever i'm needed to show a picture on the web page with ASP.NET MVC. As you recognize there's not a hypertext markup language Helper for pictures yet. check out the following screen, we will not see a picture here:

Before proceeeding during this article, let me share the sample data source here:

Data Source & Controller

View

As in the above image, the first one (@Html.DisplayFor…) is generated by scaffolding on behalf of me (marked as a comment within the above view) and the second one is an alternative that may work. So, we do not have a hypertext markup language helper to manage pictures exploitation Razor syntax! We will develop an extension method for this that will allow us to work with pictures. Let's start.

Now, Add a class file using the following code: using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication8.Models
{   
public static class ImageHelper
    {
        public static MvcHtmlString Image(this HtmlHelper helper, string src, string altText, string height)
        {
            var builder = new TagBuilder("img");
          builder.MergeAttribute("src", src);            builder.MergeAttribute("alt", altText);
            builder.MergeAttribute("height", height);
            return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
        }
    }
}


The above "Image" function has the "MvcHtmlString" type and can settle for a four-parameter helper (helper sort "image"), src (image path), altText (alternative text) and height (height of image) and will return a "MvcHtmlString" type. In the view, comment-out the last line (HTML style approach) and use the new extended technique for the image, as in:

Note: Please note to use "@using MvcApplication8.Models" namespace on every view page to enable this new HtmlHelper. If you set a breakpoint on the extension method then you'll notice that the method returns the exact markup that we need.

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. You will not be charged a cent for trying our service for the next 3 days. Once your trial period is complete, you decide whether you'd like to continue.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Add an Area to Your Project

clock April 13, 2015 06:18 by author Rebecca

In Visual Studio 2013, what you have to do if you wanted to add area to your project is right click then selected “Add” and then “Area”, typed in the name for the Area and then Visual Studio would scaffold this. The output would be a new folder called Area, then within this you would have your standard MVC folders (Controllers, Models, Views) along with some other files that would automagically register the area within the project.

 

But in Visual Studio 2015 Preview, this Add > Area option is currently not there. I am not sure if it will be added in at some point, but for now the process is more manual but very very simple.

Here an the steps to add an Area to your project:

Assuming you have created a new Asp.Net 5 Web Application, and can see all the lovely new file types like bower.json, config.json, project.json along with the new folder structure that includes the new wwwroot folder.

Step 1

Right click on your MVC project and add a new Folder named “Areas”, then right click on this new folder and create a new folder to match the name of your area, e.g. “MyArea”. Right click again on this new folder and add a Controllers and Views folder. You want to end up with this:

Step 2

Add a new MVC Controller Class to your Controllers folder named HomeController. By default VS will add the basic code for your controller + and Index view. Now once you have this, decorate the HomeController class with a new Attribute called Area. Name this after your area which in this case is “MyArea”.

[Area("MyArea")]
public class HomeController : Controller
{
    // GET: /<controller>/
    public IActionResult Index()
    {
        return View();
    }
}

Step 3

You will now need to tell your MVC app to use a new Area route similar to AreaRegistration in MVC 4/5 but much simpler. Open up the Startup.cs file and then Map a new route within the existing app.UseMvc(routes => code.

// Add MVC to the request pipeline.
app.UseMvc(routes =>
{

    // add the new route here.
    routes.MapRoute(name: "areaRoute",
        template: "{area:exists}/{controller}/{action}",
        defaults: new { controller = "Home", action = "Index" });

    routes.MapRoute(
        name: "default",
        template: "{controller}/{action}/{id?}",
        defaults: new { controller = "Home", action = "Index" });

});

Your new route will work exactly the same as the “default” route with the addition of the area. So if you now create an Index view for your HomeController and navigate to /MyArea/Home or /MyArea/Home/Index you will see your index view.

Yes, it's done!

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 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 MVC 6 Hosting Russia - HostForLIFE.eu :: How to show Multiple Models in a Single View Using Dynamically Created Object ?

clock April 9, 2015 08:11 by author Scott

In this article I will disclose about How to show Multiple Models in a Single View utilizing dynamically created object in ASP.NET MVC. Assume I have two models, Course and Student, and I have to show a list of courses and students within a single view. By what means would we be able to do this? And here is the code that I used:

Model(Student.cs)
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVCMultipleModelsinView.Models
{
    public class Student
    {
        public int studentID { get; set; }
        public string studentName { get; set; }
        public string EnrollmentNo { get; set; }
        public string courseName { get; set; }
        public List<Student> GetStudents()
        {
            List<Student> students = new List<Student>();
            students.Add(new Student { studentID = 1, studentName = "Peter", EnrollmentNo = "K0001", courseName ="ASP.NET"});
            students.Add(new Student { studentID = 2, studentName = "Scott", EnrollmentNo = "K0002", courseName = ".NET MVC" });
            students.Add(new Student { studentID = 3, studentName = "Rebecca", EnrollmentNo = "K0003", courseName = "SQL Server" });
            return students;
        }
    }
}


Model(Course.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVCMultipleModelsinView.Models
{
    public class Course
    {
        public int courseID { get; set; }
        public string courseCode { get; set; }
        public string courseName { get; set; }
        public List<Course> GetCourses()
        {
            List<Course> Courses = new List<Course>();
            Courses.Add(new Course { courseID = 1, courseCode = "CNET", courseName = "ASP.NET" });
            Courses.Add(new Course { courseID = 2, courseCode = "CMVC", courseName = ".NET MVC" });
            Courses.Add(new Course { courseID = 3, courseCode = "CSVR", courseName = "SQL Server" });
            return Courses;
        }
    }
}


Controller (CourseStudentController.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Dynamic;
using MVCMultipleModelsinView.Models;
namespace MVCMultipleModelsinView.Controllers
{
    public class CourseStudentController : Controller
   {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome!";
            dynamic model = new ExpandoObject();
            Student stu = new Student();
            model.students = stu.GetStudents();
            Course crs = new Course();
            model.courses = crs.GetCourses();
            return View(model);
       }
    }
}

View(Index.cshtml):
@using MVCMultipleModelsinView.Models;
@{
   ViewBag.Title = "Index";
}
<h2>@ViewBag.Message</h2>
<style type="text/css">
table
    {
        margin: 4px;
        border-collapse: collapse;
        width: 500px;
        font-family:Tahoma;
   }
    th
    {
        background-color: #990000;
        font-weight: bold;
        color: White !important;
    }
    table th a
    {
        color: White;
        text-decoration: none;
    }
    table th, table td
    {
        border: 1px solid black;
        padding: 5px;
    }
</style>
<p>
    <b>Student List</b></p>
<table>
    <tr>
        <th>
            Student Id
        </th>
        <th>
            Student Name
        </th>
        <th>
            Course Name
        </th>
        <th>
            Enrollment No
        </th>
    </tr>
    @foreach (Student stu in Model.students)
    {
        <tr>
            <td>@stu.studentID
            </td>
            <td>@stu.studentName
            </td>
            <td>@stu.courseName
            </td>
            <td>@stu.EnrollmentNo
            </td>
        </tr>
    }
</table>
<p> 
 <b>Course List</b></p>
<table>
   <tr>
       <th>
            Course Id
        </th>
        <th>
            Course Code
        </th>
        <th>
            Course Name
       </th>
    </tr>
    @foreach (Course crs in Model.courses)
    {
        <tr>
            <td>@crs.courseID
            </td>
            <td>@crs.courseCode
            </td>
            <td>@crs.courseName
        </tr>
    }
</table>

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