March 6, 2015 06:22 by
Peter
Today, In this article I will tell you about Create Web API with ASP.NET 5, run outside IIS application. First step, open visual studio and then make a console application as you can see on the picture below:
Create the Web API & OWIN Packages
Go to Tools menu, choose Library Package Manager, then select Package Manager Console. In the Package Manager Console window, enter the following code:
Install-Package Microsoft.AspNet.WebApi.OwinSelfHost
Then, right click the project. Create new class named Startup.cs and add the following code:
public class Startup
{
// This code configures Web API. The Startup class is specified as a type
// parameter in the WebApp.Start method.
public void Configuration(IAppBuilder appBuilder)
{
// Configure Web API for self-host.
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
appBuilder.UseWebApi(config);
}
}
Now create a Web API controller class. In Solution Explorer, right click the project & choose Add / Class to add a new class. I named it: HelloController. Then write the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
namespace SelfHostWebApi
{
public class HelloController : ApiController
{
// GET api/values/5
public string Get(int id)
{
return "Hello API";
}
}
}
Open Program.cs and add write the code below, inside main method:
using Microsoft.Owin.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace SelfHostWebApi
{
class Program
{
static void Main(string[] args)
{
string baseAddress = "http://localhost:9000/";
// Start OWIN host
using (WebApp.Start<Startup>(url: baseAddress))
{
// Create HttpCient and make a request to api/values
HttpClient client = new HttpClient();
var response = client.GetAsync(baseAddress + "api/hello").Result;
Console.WriteLine(response);
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}
Console.ReadLine();
} }
}
Finally, your self hosted Web API is ready. You will see the output like the picture below when you Run it.
HostForLIFE.eu ASP.NET 5 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.
February 27, 2015 06:16 by
Peter
In this post I will tell you about select or deselect all checkbox inside gridview using jquery in ASP.NET 5. First, create a new project and then write the following code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewSelectAll.aspx.cs"
Inherits="GridViewSelectAll" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#<%=gvProducts.ClientID%> input[id$='chkAll']:checkbox").click(function () {
$("#<%=gvProducts.ClientID%> input[id*='chkSelected']:checkbox").attr('checked', $(this).is(':checked'));
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView runat="server" ID="gvProducts" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<input type="checkbox" id="chkAll" runat="server" value='<%#Eval("ProductID") %>' />
</HeaderTemplate>
<ItemTemplate>
<input type="checkbox" id="chkSelected" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ProductName" HeaderText="ProductName" />
<asp:BoundField DataField="Description" HeaderText="Description" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class GridViewSelectAll : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
gvProducts.DataSource = ProductDAL.GetProducts();
gvProducts.DataBind();
}
}
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public string Description { get; set; }
}
public class ProductDAL
{
public static List<Product> GetProducts()
{
return new List<Product>()
{
new Product() {ProductID = 1, ProductName = "Product01", Description = "Example01"},
new Product() {ProductID = 2, ProductName = "Product02", Description = "Example02"},
new Product() {ProductID = 3, ProductName = "Product03", Description = "Example03"},
new Product() {ProductID = 4, ProductName = "Product04", Description = "Example04"},
new Product() {ProductID = 5, ProductName = "Product05", Description = "Example05"},
};
}
}
HostForLIFE.eu ASP.NET 5 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.
February 16, 2015 06:48 by
Peter
In this article, I will tell you how to create form validation in AngularJs and ASP.NET 5. In most of Web Apps, we require user to register on the application. I need to do some action like Form validation , so that user can not submit a Invalid form. There are too many way to validate a form in Client side.
Here we are using AngularJs for the form validation. AngularJs Provide many form Validation Directives, We will use then to validate our form. Now, let’s create new project. First, Add a Employee class and write the code below:
namespace FormValidationInAj.Models
{
public class Employee
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public int Age { get; set; }
}
}
Create an Empty Home Controller
using System.Web.Mvc;
namespace FormValidationInAj.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
}
Add Index view corresponding to Index action with this code:
@model FormValidationInAj.Models.Employee
<div ng-controller="myCntrl" class="divForm">
<form name="registerForm" novalidate ng-submit="Save(registerForm.$valid)">
@Html.AntiForgeryToken()
<fieldset>
<legend>Employee</legend>
<div class="editor-label">
@Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field form-group">
<input type="text" ng-model="firstName" name="firstName" ng-required="true" />
<p ng-show="registerForm.firstName.$error.required && !registerForm.firstName.$pristine" class=" error">First Name Required</p>
</div>
<div class="editor-label">
@Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field form-group">
<input type="text" ng-model="lastName" name="lastName" />
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field form-group">
<input type="email" ng-model="Email" name="Email" ng-required="true" />
<p ng-show="registerForm.Email.$error.required && !registerForm.Email.$pristine" class="error">Email Required</p>
<p ng-show="registerForm.Email.$error.email && !registerForm.Email.$pristine" class="error">Invalid Email</p>
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Age)
</div>
<div class="editor-field form-group">
<input type="number" ng-model="Age" name="Age" ng-required="true" />
<p ng-show="registerForm.Age.$error.required && !registerForm.Age.$pristine" class="error">Age Required</p>
<p ng-show="registerForm.Age.$error.number && !registerForm.Age.$pristine" class="error">Invalid Age </p>
</div>
<p>
<input type="submit" value="Create" class="btn btn-primary" />
</p>
</fieldset>
</form>
</div>
Above I even have used AngularJs directives for form validation.
- Required :using ng-required="true", validated a input field that's required.
- Email : using Type="email" property of input field, validate Email address.
- Number : using Type="number" property of input field, validate number field.
There are several form validation directives in AngularJs.
- To show the error message, I even have used Error Name of AngularJs.
- To show error message only if used has been interacted with form, unless Error message are going to be hidden, I even have used $pristine. $pristine : it'll be true If user has not interacted with form yet.
Now, Add 2 new Js file.
module.js
var app = angular.module("myApp", []);
Controller.js
app.controller("myCntrl", function ($scope, $http) {
$scope.Save = function (Valid) {
if (!Valid) {
alert("Invalid form");
return;
} else {
alert("It's Great. Form Submitted");
}
}
});
Modilfy your _Layout.cshtml file. I have included required Js file for angularJs.
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/css")
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/Angular/Module.js"></script>
<script src="~/Scripts/Angular/Controller.js"></script>
<style>
.divForm{
margin: 15px 50px;
padding: 0;
width: 30%;
}
</style>
</head>
<body>
@RenderBody()
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
</body>
</html>
Output:
HostForLIFE.eu ASP.NET 5 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.
February 13, 2015 05:55 by
Peter
In this tutorial, I will show you how to create custom config section in ASP.NET 5. You can extend ASP.NET configuration settings with XML configuration elements of your own. To do this, you create a custom configuration section handler.
The handler should be a ASP.NET Framework class that inherits from the System.Configuration.ConfigurationSection class. The section handler interprets and processes the settings that are defined in XML configuration elements in a specific section of a web.config file. You'll read and write these settings through the handler's properties.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
namespace CustomConfigSection
{
public class LoginRedirectByRoleSection : ConfigurationSection
{
[ConfigurationProperty("roleRedirects")]
public RoleRedirectCollection RoleRedirects
{
get
{
return (RoleRedirectCollection)this["roleRedirects"];
}
set
{
this["roleRedirects"] = value;
}
}
}
public class RoleRedirect : ConfigurationElement
{
[ConfigurationProperty("role", IsRequired = true)]
public string Role
{
get
{
return (string)this["role"];
}
set
{
this["role"] = value;
}
}
[ConfigurationProperty("url", IsRequired = true)]
public string Url
{
get
{
return (string)this["url"];
}
set
{
this["url"] = value;
}
}
}
public class RoleRedirectCollection : ConfigurationElementCollection
{
public RoleRedirect this[int index]
{
get
{
return (RoleRedirect)BaseGet(index);
}
}
public RoleRedirect this[object key]
{
get
{
return (RoleRedirect)BaseGet(key);
}
}
protected override ConfigurationElement CreateNewElement()
{
return new RoleRedirect();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((RoleRedirect)element).Role;
}
}
}
<configSections>
<section name="loginRedirectByRole" type="CustomConfigSection.LoginRedirectByRoleSection,CustomConfigSection" allowLocation="true" allowDefinition="Everywhere" />
</configSections>
<loginRedirectByRole>
<roleRedirects>
<add role="Administrator" url="~/Admin/Default.aspx" />
<add role="User" url="~/User/Default.aspx" />
</roleRedirects>
</loginRedirectByRole>
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using CustomConfigSection;
namespace CustomConfigSection
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
LoginRedirectByRoleSection roleRedirectSection = (LoginRedirectByRoleSection)ConfigurationManager.GetSection("loginRedirectByRole");
foreach (RoleRedirect roleRedirect in roleRedirectSection.RoleRedirects)
{
if (Roles.IsUserInRole("", roleRedirect.Role))
{
Response.Redirect(roleRedirect.Url);
}
}
}
}
}
HostForLIFE.eu ASP.NET 5 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.
February 9, 2015 09:39 by
Peter
With this article, I will tell you about how to to read pdf document properties in ASP.NET 5. We know that there is no- such in-built class in .NET framework that read the pdf document. In this example,I will used third-party library iTextSharp. And here is the code that I used for this article:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PdfPropertiesReader.aspx.cs" Inherits="PdfPropertiesReader" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="pdfProperties" runat="server">
</div>
</div>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Read Pdf Properties" /> </form>
</body>
</html>
using System;
using System.Collections;
using System.Collections.Generic;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Text;
public partial class PdfPropertiesReader : System.Web.UI.Page
{
private const string FileNmae = @"C:\\temp\\asp.pdf";
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
StringBuilder stringBuilder = new StringBuilder();
// create a reader (constructor overloaded for path to local file or URL)
PdfReader reader = new PdfReader(FileNmae);
// total number of pages
int n = reader.NumberOfPages;
// size of the first page
Rectangle psize = reader.GetPageSize(1);
float width = psize.Width;
float height = psize.Height;
Console.WriteLine("Size of page 1 of {0} => {1} × {2}", n, width, height);
// file properties
Hashtable infodict = reader.Info;
foreach (DictionaryEntry kvp in infodict)
{
stringBuilder.Append(kvp.Key + "=>" + kvp.Value + "</br>");
}
pdfProperties.InnerHtml = stringBuilder.ToString();
}
catch (Exception exception)
{
Response.Write(exception.Message);
}
}
}
HostForLIFE.eu ASP.NET 5 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.
February 6, 2015 07:00 by
Peter
In this post I am going to tell you how to get IP Address of the client machine in ASP.NET 5 with C#.Net or fetch/discover IP location of the client or server machine utilizing ASP.NET with C#.Net. You can likewise put this code in your site to get or retrieve users IP address also you count the unique visitor in your website. In numerous site use this kind of usefulness so he can see that which user is visited our website. So you can likewise utilize or set this code to your site for getting the listof IP location of the users machine that are gone by your site.
The following code is to get the client IP address in ASP.NET:
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="RetriveUserIpAddressInAspNet.aspx.cs" Inherits="ProjectDemo_Asp.et.RetriveUserIpAddressInAspNet" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
Client Id Address:
<asp:Label ID="lblIPddress" runat="server" Text=""
style="color: #FF0066; font-size: x-large"></asp:Label>
</div>
</form>
</body>
</html>
C#.Net code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ProjectDemo_Asp.et
{
public partial class RetriveUserIpAddressInAspNet : System.Web.UI.Page
{
public void Page_Load(Object sender, EventArgs e)
{
//code for print the time when the page loaded initially
lblIPddress.Text= GetLanIPAddress().Replace("::ffff:", "");
}
/*
Method to get the IP Address of the User
*/
public String GetLanIPAddress()
{
String ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
{
ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
return ip;
}
}
}
HostForLIFE.eu ASP.NET 5 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.
February 2, 2015 07:10 by
Peter
In this article, I will explain you about creating a custom configuration sections in ASP.NET 5. We want to extend ASP.NET configuration settings using XML configuration elements of your own. To do this, we produce a custom configuration section handler. The handler should be a .NET Framework class that inherits from the System.Configuration.ConfigurationSection class. The section handler interprets and processes the settings that are outlined in XML configuration elements in a specific section of a web.config file. We willl browse and write these settings through the handler's properties. And here is the code that I used:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
namespace CustomConfigSection
{
public class LoginRedirectByRoleSection : ConfigurationSection
{
[ConfigurationProperty("roleRedirects")]
public RoleRedirectCollection RoleRedirects
{
get
{
return (RoleRedirectCollection)this["roleRedirects"];
}
set
{
this["roleRedirects"] = value;
}
}
}
public class RoleRedirect : ConfigurationElement
{
[ConfigurationProperty("role", IsRequired = true)]
public string Role
{
get
{
return (string)this["role"];
}
set
{
this["role"] = value;
}
}
[ConfigurationProperty("url", IsRequired = true)]
public string Url
{
get
{
return (string)this["url"];
}
set
{
this["url"] = value;
}
}
}
public class RoleRedirectCollection : ConfigurationElementCollection
{
public RoleRedirect this[int index]
{
get
{
return (RoleRedirect)BaseGet(index);
}
}
public RoleRedirect this[object key]
{
get
{
return (RoleRedirect)BaseGet(key);
}
}
protected override ConfigurationElement CreateNewElement()
{
return new RoleRedirect();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((RoleRedirect)element).Role;
}
}
}
<configSections>
<section name="loginRedirectByRole" type="CustomConfigSection.LoginRedirectByRoleSection,CustomConfigSection" allowLocation="true" allowDefinition="Everywhere" />
</configSections>
<loginRedirectByRole>
<roleRedirects>
<add role="Administrator" url="~/Admin/Default.aspx" />
<add role="User" url="~/User/Default.aspx" />
</roleRedirects>
</loginRedirectByRole>
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using CustomConfigSection;
namespace CustomConfigSection
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
LoginRedirectByRoleSection roleRedirectSection = (LoginRedirectByRoleSection)ConfigurationManager.GetSection("loginRedirectByRole");
foreach (RoleRedirect roleRedirect in roleRedirectSection.RoleRedirects)
{
if (Roles.IsUserInRole("", roleRedirect.Role))
{
Response.Redirect(roleRedirect.Url);
}
}
}
}
}
HostForLIFE.eu ASP.NET 5 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.
January 30, 2015 05:50 by
Peter
In this article i will explain you how to Filter and Sorting in GridView using DataView in ASP.NET 5. First, you must create a new project and write the below code in ASP.NET:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Filter and Sorting in GridView using DataView</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
Enter ID:
</td>
<td>
<asp:TextBox ID="txtId" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Enter User Name:
</td>
<td>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnSearch" runat="server" Text="Search"
onclick="btnSearch_Click"></asp:Button>
</td>
</tr>
</table>
<asp:GridView ID="GridFilter" runat="server" BackColor="White" BorderColor="#CC9966"
AllowPaging="True" PageSize="5" BorderStyle="Solid" AutoGenerateColumns="False"
BorderWidth="1px" CellPadding="4" Font-Names="Georgia" DataKeyNames="User_ID"
Font-Size="Small" OnSorting="GridFilter_Sorting" AllowSorting="true">
<Columns>
<asp:BoundField DataField="User_ID" HeaderText="User_ID" SortExpression="User_ID" /> <asp:BoundField DataField="UserName" HeaderText="User Name" SortExpression="UserName" />
<asp:BoundField DataField="Gender" HeaderText="Gender" SortExpression="Gender" />
<asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />
</Columns>
<FooterStyle BackColor="Tan" />
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
</asp:GridView>
</div>
</form>
</body>
</html>
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class GridRowFilter : System.Web.UI.Page
{
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridFilter.DataSource = BindUsers();
GridFilter.DataBind();
}
}
private DataSet BindUsers()
{
ds = new DataSet();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
SqlCommand cmd = new SqlCommand("Select User_ID,UserName,Gender,Country from User_Details", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
return ds;
}
protected void btnSearch_Click(object sender, EventArgs e)
{
try
{
ds = BindUsers();
DataTable dt = new DataTable();
dt = ds.Tables[0];
DataView dvData = dt.DefaultView;
string strFilter = " 1=1 ";
if (!string.IsNullOrEmpty(txtId.Text))
strFilter = strFilter + " And User_ID = " + Convert.ToInt32(txtId.Text);
if (!string.IsNullOrEmpty(txtUserName.Text))
strFilter = strFilter + " And UserName Like '%" + txtUserName.Text + "%'"; dvData.RowFilter = strFilter;
GridFilter.DataSource = dvData;
GridFilter.DataBind();
}
catch (Exception ex)
{
throw ex;
}
}
protected void GridFilter_Sorting(object sender,GridViewSortEventArgs e)
{
try
{
DataSet ds = BindUsers();
DataTable dt = new DataTable();
dt = ds.Tables[0];
DataView dvData = dt.DefaultView;
if (ViewState["SortDirection"] != null && ViewState["SortDirection"].ToString() != "")
dvData.Sort = e.SortExpression + " " + ConvertSortDirection(ViewState["SortDirection"].ToString());
else
dvData.Sort = e.SortExpression + " " + ConvertSortDirection("ASC");
GridFilter.DataSource = dvData;
GridFilter.DataBind();
}
catch (Exception ex)
{
throw ex; }
}
private string ConvertSortDirection(string sortDireciton)
{
try
{
if (sortDireciton != null)
{
switch (sortDireciton)
{
case "ASC":
ViewState["SortDirection"] = "DESC";
break;
case "DESC":
ViewState["SortDirection"] = "ASC";
break;
}
}
return sortDireciton;
}
catch (Exception err)
{
throw err;
}
}
}
In VB.NET
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Partial Public Class GridRowFilter
Inherits System.Web.UI.Page
Private ds As DataSet
Protected Sub Page_Load(sender As Object, e As EventArgs)
If Not IsPostBack Then
GridFilter.DataSource = BindUsers()
GridFilter.DataBind()
End If
End Sub
Private Function BindUsers() As DataSet
ds = New DataSet()
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("con").ConnectionString) Dim cmd As New SqlCommand("Select User_ID,UserName,Gender,Country from User_Details", con) Dim da As New SqlDataAdapter(cmd)
da.Fill(ds)
Return ds
End Function
Protected Sub btnSearch_Click(sender As Object, e As EventArgs)
Try
ds = BindUsers()
Dim dt As New DataTable()
dt = ds.Tables(0)
Dim dvData As DataView = dt.DefaultView
Dim strFilter As String = " 1=1 "
If Not String.IsNullOrEmpty(txtId.Text) Then
strFilter = strFilter & " And User_ID = " & Convert.ToInt32(txtId.Text)
End If
If Not String.IsNullOrEmpty(txtUserName.Text) Then
strFilter = (strFilter & " And UserName Like '%") + txtUserName.Text & "%'"
End If
dvData.RowFilter = strFilter
GridFilter.DataSource = dvData
GridFilter.DataBind()
Catch ex As Exception
Throw ex
End Try
End Sub
Protected Sub GridFilter_Sorting(sender As Object, e As GridViewSortEventArgs)
Try
Dim ds As DataSet = BindUsers()
Dim dt As New DataTable()
dt = ds.Tables(0)
Dim dvData As DataView = dt.DefaultView
If ViewState("SortDirection") IsNot Nothing AndAlso ViewState("SortDirection").ToString() <> "" Then
dvData.Sort = e.SortExpression & " " & ConvertSortDirection(ViewState("SortDirection").ToString())
Else
dvData.Sort = e.SortExpression & " " & ConvertSortDirection("ASC")
End If
GridFilter.DataSource = dvData
GridFilter.DataBind()
Catch ex As Exception
Throw ex
End Try
End Sub
Private Function ConvertSortDirection(sortDireciton As String) As String
Try
If sortDireciton IsNot Nothing Then
Select Case sortDireciton
Case "ASC"
ViewState("SortDirection") = "DESC"
Exit Select
Case "DESC"
ViewState("SortDirection") = "ASC"
Exit Select
End Select
End If
Return sotDireciton
Catch err As Exception
Throw err
End Try
End Function
End Class
HostForLIFE.eu ASP.NET 5 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.
January 26, 2015 06:23 by
Peter
At this short article, we will Create validation control's Error messages in Alert box in ASP.NET 5. First step, you need to know about how to show validation control's Error messages in Alert box in ASP.NET. Then, write the following code:
ASP.NET
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>How to show validation control's Error messages in Alert box in ASP.NET</title>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>
<asp:Label ID="lblName" runat="server" Text="Name"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtName" runat="server" ValidationGroup="Validation"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvName" runat="server" ControlToValidate="txtName"
Display="None" ErrorMessage="Name is Required" ValidationGroup="Validation"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblGender" runat="server" Text="Gender"></asp:Label>
</td>
<td>
<asp:DropDownList ID="ddlGender" runat="server" ValidationGroup="Validation">
<asp:ListItem Selected="True" Value="0">--Select--</asp:ListItem>
<asp:ListItem Value="1">Male</asp:ListItem>
<asp:ListItem Value="2">Female</asp:ListItem>
</asp:DropDownList>
<asp:CompareValidator ID="CVGender" runat="server" ControlToValidate="ddlGender"
Display="None" ErrorMessage="Gender is Required" Operator="NotEqual" ValidationGroup="Validation"
ValueToCompare="0"></asp:CompareValidator>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblEmail" runat="server" Text="Email Address"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtEmail" runat="server" ValidationGroup="Validation"></asp:TextBox>
<asp:RegularExpressionValidator ID="regEmail" runat="server" ControlToValidate="txtEmail"
Display="None" ValidationGroup="Validation" ErrorMessage="Enter Valid Email address "
ValidationExpression="^([a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]){1,70}$">
</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblValidation" runat="server" Text="* Marked fields are mandatory"
ForeColor="Red"></asp:Label>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btnShowAlert" runat="server" Text="Show Alert" ValidationGroup="Validation" />
<asp:ValidationSummary ID="ValidationSummary1" runat="server" ShowMessageBox="True"
ShowSummary="False" ValidationGroup="Validation" />
</td>
</tr>
</table>
</form>
</body>
</html>
And here is the result:
HostForLIFE.eu ASP.NET 5 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.
January 19, 2015 07:19 by
Peter
This article will explain you how Create DropDownList Validation with JQuery JavaScript in ASP.NET 5 where DropDown is either bind with SqlDataSource or listItems. Place one drop down and button on the page in design view and add JQuery javascript file in solution and add it's reference in head section of page. Then, Write following JQuery script in head section of page.
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#Button1').on('click', function(e) {
var selectedText = $('#DropDownList1
option:selected').text().toLowerCase();
if (selectedText == 'select')
{
alert('Please select any language.');
e.preventDefault();
}
else
alert('You selected ' + selectedText);
})
})
</script>
</head>
HTML Code for Drop Down And Button
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem>C#</asp:ListItem>
<asp:ListItem>VB</asp:ListItem>
<asp:ListItem>Java</asp:ListItem>
<asp:ListItem>C</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Button" />
Now if DropDownList is obtaining populated from database by SqlDataSource then we'd like to line AppendDataBoundItems property of dropdown to true and add one list item with text choose at 0th index in Page_Load event.
<asp:DropDownList ID="DropDownList2" runat="server"
AppendDataBoundItems="True"
DataSourceID="SqlDataSource1"
DataTextField="ProductName"
DataValueField="ProductID">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:TestDbConnectionString %>"
SelectCommand="SELECT [ProductID], [ProductName] FROM [Products]">
</asp:SqlDataSource>
<asp:Button ID="Button2" runat="server" Text="Button" />
Next step, write the following code in code behind.
protected void Page_Load(object sender, EventArgs e)
{
DropDownList2.Items.Add(new ListItem("select", "0"));
}
Then write following JQuery code in head section of html source of page.
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#Button2').on('click', function(e) {
var selectedValue = $('#DropDownList2').val();
if (selectedValue == 0)
{
alert('Please select any product.');
e.preventDefault();
}
else
alert('you selected product with ID ' + selectedValue);
})
})
</script>
If you wanna use the JavaScript code Instead of Jquery then write the following code:
<script type="text/javascript">
function Validation() {
var selectedValue = document.getElementById('<%=DropDownList2.ClientID%>').value;
if (selectedValue == "0")
{
alert("Please Select Product");
}
else {
alert("You selected " + selectedValue);
}
}
</script>
Finally, Call the function bellow in OnClientClick Event of button:
<asp:Button ID="Button2" runat="server" Text="Button" OnClientClick="Validation>
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 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.