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