European ASP.NET MVC Hosting

BLOG about Latest ASP.NET MVC Hosting and Its Technology - Dedicated to European Windows Hosting Customer

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 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 MVC 6 Hosting UK - HostForLIFE.eu :: How to Search Records with Ajax in ASP.NET MVC ?

clock March 13, 2015 07:17 by author Peter

Today, I will tell you about how to search records in MVC with Ajax and jQuery. This code will filter out all matching records group by table column name.

First thing that you should do is create an empty ASP.NET MVC project. Now, add two class to your model. Employee and DemoContext and write the following code:
namespace SearchingDemo.Models
{
    public class Employee
    {
        [Key]
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Position { get; set; }
     }
}
namespace SearchingDemo.Models
{
    public class DemoContext : DbContext
    {
        public DbSet<Employee> Employees { get; set; }
    }
}

Add a Home Controller. Now, Add index Action to controller. and create corresponding view.
public ActionResult Index()
       {
           return View();
      }

Now, write the following code to Index View.
<link href="~/Content/Style.css" rel="stylesheet" />
<script src="~/Content/jquery-2.1.1.min.js"></script>
<script src="~/Content/CustomJs.js"></script>
<h2>Seaching Demo</h2> 
<div class="divFind">
    <table>
        <tr>
            <td>
                <input type="text" id="txtSearch" />
            </td>
            <td>
                <input type="button" id="btnSearch" value="Seach" />
            </td>
        </tr>
    </table>
</div>
<div id="divList"> 
</div>

Write the .JS code for click event on seach button to get filtered result. add following .JS code.
$(document).ready(function () {
    $('#btnSearch').on('click', function () {
        var getkey = $('#txtSearch').val();
        $.ajax({           
        type: 'POST',
            contentType: 'application/json; charset=utf-8',
            url: 'Home/Search',
            data: "{ 'searchKey':' " + getkey + "' }",
            success: function (data) {
                BindData(data);
            },            
            error: function (data) {
                alert('Error in getting result');
            }
        });
   });
}); 
function BindData(data) {
    var ulList = '<ul>';
    var resultType = ["FirstName", "LastName", "Position"];
    $.each(data, function (i, d) {
        ulList += '<li class="SeachType">' + resultType[i] + '</li>';
        if (d.length > 0) {
            $.each(d, function (key, value) {
                ulList += '<li>' + value.FirstName + ' - ' + value.LastName + ' - ' + value.Position + '</li>'
            });
        } else {            
        ulList += '<li><span class="red">No Results</span></li>';
        }
    });
    ulList += '</ul>'
    $('#divList').html(ulList);
}

Javascript code calling search function, which is written in controller. Add search function to your controller.
public JsonResult Search(string searchKey)
       {
           DemoContext dbObj = new DemoContext();
           var getKey = searchKey.Trim();
           var getFirstName = dbObj.Employees.Where(n => n.FirstName.Contains(getKey)).ToList(); 
           var getLastName = dbObj.Employees.Where(n => n.LastName.Contains(getKey)).ToList(); 
           var getPostion = dbObj.Employees.Where(n => n.Position.Contains(getKey)).ToList(); 
           IList<IList<Employee>> getTotal = new List<IList<Employee>>();
           getTotal.Add(getFirstName);
           getTotal.Add(getLastName);
           getTotal.Add(getPostion);
           int count = getTotal.Count();
           return Json(getTotal);
      }

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 Germany - HostForLIFE.eu :: How to Display Empty Data Text in WebGrid in ASP.NET MVC

clock March 6, 2015 06:57 by author Peter

In this case we disclose that how to show Empty Data Text in webgrid in MVC with ASP.NET.

There is no facility in webgrid to show empty datatext automatically, so we need to manually write or characterize the code for this.

Let's see a simple tips that demonstrates to show Empty Data or unfilled information message in ASP.NET MVC WebGrid by utilizing WebGrid web helper class. Here in this post we will check the  model in the event that it  has no data then show a message, like the EmptyDataText property of the ASP.NET GridView.

To utilize the WebGrid web assistant as a part of MVC application, you need to first make an article reference to the WebGrid class and utilize the GetHtml() method that renders the grid. To use the WebGrid web helper in mvc application, you have to first create an object reference to the WebGrid class and use the GetHtml() method that renders the grid.
@{
                Var grid=new WebGrid(Model);
@grid.GetHtml();
}
To Display an Empty Data Text in Webgrid when the Model has no data or no record, just you have to write  following one:
@if(Model.Count>0)
@{
Var grid=new WebGrid(Model);
@grid.GetHtml();
}
Else
<p>No Record Found</p>
}

I hope this tutorial works for you!

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 Frankfurt - HostForLIFE.eu :: How to Refresh PartialView Automatically?

clock March 5, 2015 07:07 by author Peter

In this post, I will tell you about Refresh PartialView Automatically in ASP.NET MVC 6.  First thing you can do is Create a MVC app on Visual Studio and then add two Classes to your model folder.

using System.ComponentModel.DataAnnotations;
namespace AutoRefresh.Models
{
    public class Employee
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public string ImagePath { get; set; }
    }
}


using System.Data.Entity;
namespace AutoRefresh.Models
{
    public class DemoContext:DbContext
    {
        public DbSet<Employee> employee { get; set; }
    }
}

Now, add a Home Controller and write the following code:
using System;
using System.Linq;
using System.Web.Mvc;
using AutoRefresh.Models;
using System.Web.UI;
namespace AutoRefresh.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            using (DemoContext dbObj = new DemoContext())
            {
               var empList = dbObj.employee.ToList();
                return View(empList);
           }
    }
        [OutputCache(Location = OutputCacheLocation.Client, VaryByParam = "none", Duration = 2)]
        public PartialViewResult _employeeShow()
       {
            using (DemoContext dbObj = new DemoContext())
            {
                var empList = dbObj.employee.ToList();
                int MinId = empList.Min(a => a.Id);
                int MaxId = empList.Max(a => a.Id);
               //generate a random number
                int GetRandomId = new Random().Next(MinId, (MaxId + 1));
                var getRandomemployee=empList.Find(a => a.Id == GetRandomId);
                return PartialView("_employeeShow", getRandomemployee);
            }
        }
     }
}


From the above code, I used OutputCache to get Data from Cache. Next step, add a PartialView _employeeShow to show the Employee.
@model AutoRefresh.Models.Employee
<div class="divEmployee" style="margin-left: 50px;">
    <img src="@Model.ImagePath" width="100" height="100" />
    <span>@Model.Name</span>
</div>

Now , create the Index View. With this view we will load our PartialView.
@model IEnumerable<AutoRefresh.Models.Employee>
@{
    ViewBag.Title = "Index";
}
<script src="~/Scripts/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        setInterval(function () {
            $('#Employee').load('/Home/_employeeShow')
        },2000);
    });
</script>
<h2>Employee</h2>
<div id="Employee">
    @Html.Partial("_employeeShow", Model.FirstOrDefault())
</div>

Using Jquery, I’m loading the PartialView in every 2 seconds.

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 :: Check Username Availability in ASP.NET MVC with Ajax and jQuery

clock February 27, 2015 06:29 by author Peter

Generally in web application, users got to register to perform some operation. Therefore every user ought to have unique username. during this tutorial we are going to see a way to check Username availability Instantly using Ajax and jQuery. First, let’s create an empty ASP.NET 6 project and then Add model classes to model folder and write the following code:

using System.ComponentModel.DataAnnotations; 
namespace CheckUsernameDemo.Models
{
    public class Employee
   {
        [Key]
        public int Id { get; set; }
        public string Username { get; set; }
        public string Name { get; set; }
        public string Title { get; set; }
    }
}

Add another class
using System.Data.Entity;
namespace CheckUsernameDemo.Models
{
    public class DemoContext:DbContext
    {
        public DbSet<Employee> Employees { get; set; }
    }
}

Next step, Add a HomeController. Then an Index Action to It. Here is the code that I used:
using System.Linq;
using System.Web.Mvc;
using CheckUsernameDemo.Models;
namespace CheckUsernameDemo.Controllers
{
    public class HomeController : Controller
    {
        DemoContext dbObj = new DemoContext();
        public ActionResult Index()
        {  
            return View();
        }
    }
}

Now, make a Index View and write the following code.
@model CheckUsernameDemo.Models.Employee
@{
    ViewBag.Title = "Index";
}  
<h2>Register Here</h2>
@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()
    <table>
        <tr>
            <td> @Html.LabelFor(m => m.Username)</td>
            <td>
                @Html.TextBoxFor(m => m.Username)
            </td>
            <td>
                <label id="chkAvailable"></label>
            </td>
        </tr>
        <tr>
            <td> @Html.LabelFor(m => m.Name)</td>
           <td>
                @Html.TextBoxFor(m => m.Name)
            </td>
            <td></td>
        </tr>
        <tr>
            <td> @Html.LabelFor(m => m.Title)</td>
            <td>
                @Html.TextBoxFor(m => m.Title)
            </td>
           <td></td>
        </tr>
        <tr>            
            <td colspan="3">
                <input type="submit" value="Register" class="btnRegister"/>
            </td>
        </tr>
    </table>
}

Now in order to examine Username accessibility Instantly we are going to Ajax call on modification Event of username Textbox. But before writing jquery code we are going to add a method in Home Controller.
public string CheckUsername(string userName)
       {
           string IsAvailable;
           var getData = dbObj.Employees.FirstOrDefault(m => m.Username == userName.Trim());
           if(getData == null)
           {
               IsAvailable = "Available";
           }
           else
           {
               IsAvailable = "Not Available";
           }
           return IsAvailable;
       }

On the above code, we’ll find Employee using EntityFramework query. It will get Employee with that username then method will return Not Available otherwise Available. Now write jQuery code on change event on Username textbox.
<script type="text/javascript">
    $(document).ready(function () {
        $('#Username').on('change', function () {
           var getName = $(this).val();
            $.ajax({
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                url: 'Home/CheckUsername',
                data: "{ 'userName':' " + getName + "' }",
                success: function (data) {
                    if (data == "Available") {
                        $('#chkAvailable').html('Username Is ' + data);
                        $('#chkAvailable').css('color', 'green'); 
                    } else {
                        $('#chkAvailable').html('Usernam Is ' + data);
                        $('#chkAvailable').css('color', 'red');
                        $('#Username').focus();
                    }
                },
                error: function (data) {
                    alert('Error in Getting Result');
                }
            });
        });
    })
</script>

With that code, we are passing the current Textbox value to Controller method to Check Username Availability. And here is the output:

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.

 



ASP.NET MVC 6 Hosting UK - HostForLIFE.eu :: How to use the table to Apply Custom Filter & Pagination with AngularJS in ASP.NET MVC ?

clock February 26, 2015 06:15 by author Peter

In this article I will explain you about How to use the table to apply Custom filter and pagination with angularJS in ASP.NET MVC 6. First step, you must write down the code below to your Index View.

<div>
    <div ng-controller="EmpList">
       Select Number to show items Per Page <select ng-model="PerPageItems">
            <option value="5">5</option>
            <option value="10">10</option>
            <option value="15">15</option>
            <option value="20">20</option>
        </select>
        <div ng-show="filteredItems > 0">
            <table class="table table-striped" id="tblEmp">
                <tr>
                    <th>
                        First Name <a ng-click="orderByField='FirstName';">Sort</a>
                    </th>
                    <th>
                        Last Name <a ng-click="orderByField='LastName';">Sort</a>
                    </th>
                    <th>
                        Title <a ng-click="orderByField='Title';">Sort</a>                    
</th>
                </tr>
                <tr ng-repeat="items in empList | orderBy:orderByField | Pagestart:(currentPage-1)*PerPageItems | limitTo:PerPageItems ">                    
 <td>
                        {{items.FirstName}}
                    </td>
                    <td>
                        {{items.LastName}}
                    </td>
                    <td>
                        {{items.Title}}
                    </td>
                </tr>
            </table>
        </div>
        <div ng-show="filteredItems > 0">
            <pagination page="currentPage" total-items="filteredItems" ng-model="currentPage"  items-per-page="PerPageItems"></pagination>
        </div>
    </div>
</div>


And now, write the below code to your JS file.
var myApp = angular.module('myApp1', ['ui.bootstrap']); 
myApp.filter('Pagestart', function () {    // custom filter
    return function (input, start) {
        if (input) {
            start = +start;
            return input.slice(start);
        }
        return [];
    }
}); 
myApp.controller('EmpList', function ($scope, $http, $timeout) {
    var EmployeesJson = $http.get("/Home/GetEmployees");
    $scope.orderByField = 'FirstName';
    EmployeesJson.success(function (data) {
        $scope.empList = data;
        $scope.filteredItems = $scope.empList.length;  
        $scope.totalItems = $scope.empList.length;  // Total number of item in list.
        $scope.PerPageItems = 5;  // Intially Set 5 Items to display on page.
        $scope.currentPage = 1;   // Set the Intial currnet page
    });
    $scope.filter = function () {
        $timeout(function () {
            $scope.filteredItems = $scope.filtered.length;
        }, 10);
    };
});

Now, write the following JS Library to your View. And then, run the project. I hope this tutorial works for you!

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.



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.


Month List

Tag cloud

Sign in