Showing posts with label ASP DOT NET. Show all posts
Showing posts with label ASP DOT NET. Show all posts

Thursday, 11 August 2016

Remote Validation in MVC

What is Remote Validation??
Remote validation is a Process where we post validate field data to server, without post all form data to server.

We can validate the field before post all data to server. In simple word, we have not need to click submit button to check form validation status.

 Let's start with example :

We need a form for validation testing so for this visit my previous article  CRUD Operation in MVC
then come here.

In my previous article we have :

  •  Controller :  RegistrationContoller.cs








  • View : Insert.cshtml, see below



  •  Model Class : RegistrationDetails.cs,  see below


In MVC, Model handle all validation related activity. So Create one class for remote validation in Model folder,  class name is RemoteValidaton.cs, here we will validate three fields name, mobile number & email.





Code for RegistrationController


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using sandeepcodes.Models;//  Add ref of Model
using System.Data.Entity;

namespace sandeepcodes.Controllers
{
    public class RegistrationController : Controller
    {

        dataEntities db = new dataEntities(); // Create Connection


        // GET: Registration
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Insert()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Insert(RegistrationDetail obj)
        {
            if (ModelState.IsValid)
            {
                db.RegistrationDetails.Add(obj);
                db.SaveChanges();
                return RedirectToAction("Insert", "Registration");
            }
            else
            {
                return View(); 
            }
        }

        //Check Duplicate Mobile No
        public JsonResult mobilecheck(string MobileNo)
        {
            return Json(!db.RegistrationDetails.Any(x => x.MobileNo.Trim() == MobileNo.Trim()), 
                JsonRequestBehavior.AllowGet);

        }
        //Check Duplicate Email Id
        public JsonResult emailcheck(string EmailID)
        {
            return Json(!db.RegistrationDetails.Any(x => x.EmailID.Trim() == EmailID.Trim()),
                JsonRequestBehavior.AllowGet);

        }


        public ActionResult Details()
        {
            var list = db.RegistrationDetails.ToList();
            return View(list);
        }


        public ActionResult Edit(int? id)
        {
                RegistrationDetail empdetails = db.RegistrationDetails.Find(id);      
                return View(empdetails);
         
        }

        [HttpPost]
        public ActionResult Edit(RegistrationDetail obj)
        {
            RegistrationDetail data = db.RegistrationDetails.Find(obj.ID);
            data.Name = obj.Name;
            data.EmailID = obj.EmailID;
            data.MobileNo = obj.MobileNo;
            data.Address = obj.Address;
            data.Age = obj.Age;
            db.Entry(data).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Details");

        }

        public ActionResult Delete(int id)
        {
            RegistrationDetail detail = db.RegistrationDetails.Find(id);
            db.RegistrationDetails.Remove(detail);
            db.SaveChanges();
            return RedirectToAction("Details");
        }

    }


}

View Page Code 

Create one view page with name insert.cshtml.

In view page below mentioned scripts should be must.




Complete code are :

@model sandeepcodes.Models.RegistrationDetail
@{
    ViewBag.Title = "Registration Form";
}
<h2>Insert</h2>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script> @*For remote validation*@
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>@*For remote validation*@

@using (Html.BeginForm("Insert", "Registration", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{

    <div>
        <div style="width:300px">
            @Html.LabelFor(x => x.Name)
            @Html.TextBoxFor(x => x.Name, new { @class = "form-control" })
       @Html.ValidationMessageFor(x => x.Name, "", new { @class = "text-danger" })
        </div>

        <div style="width:300px">
            @Html.LabelFor(x => x.MobileNo)
            @Html.TextBoxFor(x => x.MobileNo, new { @class = "form-control" })
            @Html.ValidationMessageFor(x => x.MobileNo, "", new { @class = "text-danger" })
        </div>

        <div style="width:300px">
            @Html.LabelFor(x => x.EmailID)
            @Html.TextBoxFor(x => x.EmailID, new { @class = "form-control" })
            @Html.ValidationMessageFor(x => x.EmailID, "", new { @class = "text-danger" })

        </div>

        <div style="width:300px">
            @Html.LabelFor(x => x.Age)
            @Html.TextBoxFor(x => x.Age, new { @class = "form-control" })
        </div>

        <div style="width:300px">
            @Html.LabelFor(x => x.Address)
            @Html.TextBoxFor(x => x.Address, new { @class = "form-control" })
        </div>
        <div align="left">
            <br />
            <input type="submit" name="save" class="btn btn-success" value="Save" />
        </div>
</div>

}

Note :  All highlighted content are important.

  •  Insert is Action name
  • Registration is Controller name
  • ValidationMessage, return the validation status
  • If above mentioned scripts are not exist in your scripts folder then goto Manage NuGet Packages for solution and find all scripts and install it. Without these scripts remote validation will not work.


Code for RemoteValidation.cs page





using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations; // Namespace for Remote validation
using sandeepcodes.Models;//Add Ref. for RegistrationDetails Class
using System.Web.Mvc;

namespace sandeepcodes.Models
{
    [MetadataType(typeof(UserMetaData))]

    public partial class RegistrationDetail
    {

    }

    // Partial Class name should be same as that class name which you want to validate

    public class UserMetaData
    {

        [Display(Name = "User name")]
        [Required(ErrorMessage = "You forgot to enter a username.")]
        [StringLength(12, MinimumLength = 6,
        ErrorMessage = "Username must be between 6 and 12 characters.")]
        public string Name { get; set; }

        [Required(ErrorMessage = "Please Enter Mobile")]
        [Phone]// validation type
        [Display(Name = "Mobile No")]
        [StringLength(10, ErrorMessage = "The Mobile must contains 10 characters", 
            MinimumLength = 10)]
        [Remote("mobilecheck", "Registration", HttpMethod = "POST", 
            ErrorMessage = "Mobile no already exists.")]
        public string MobileNo { get; set; }

        [Display(Name = "Email")]
        [RegularExpression(@"^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$",
        ErrorMessage = "Please Enter Correct Email Address")]
        //Remote is for the remote side validation
        [Remote("emailcheck", "Registration", HttpMethod = "POST", 
            ErrorMessage = "Email ID already exists.")]
        public string EmailID { get; set; }
    }

}

 Note  : emailcheck & mobilecheck is Action name and Registration has contoller name.


Now build your solution & execute view page insert.cshtml.


 For better understand go through once my previous article CRUD Operation in MVC then come here.

 Benefits of Remote Validation

  • Time saving
  • Fast speed 
  • Don't need to wait post entire form to server, you can check validate filed on tab changed.



Wednesday, 5 February 2014

How we can send mail in C#??

How we can send mail through C#??

Put this code into head tag

<head runat="server"> 
<title></title> 
<script type="text/javascript"> 
function ok() { 
alert('Your mail has been sent succuessfully'); 

</script> 
</head> 

Put this code into body tag

<div> 
<table align="center"> 
<tr><td>To</td><td><asp:TextBox ID="to" runat="server"></asp:TextBox></td></tr></br> 
<tr> <td> subject</td><td><asp:TextBox ID="sub" runat="server"></asp:TextBox></td></tr></br> 

<tr><td>message</td><td><asp:TextBox ID="message" runat="server" 
TextMode="MultiLine" Height="120px" Width="278px"></asp:TextBox></td></tr></br> 

<tr> <td></td><td><asp:Button ID="btn" runat="server" Text="send" 
onclick="btn_Click" Height="26px" Width="101px" /></td></tr> 
</table> 
</div> 

C# code


using System.Net.Mail; 

protected void clear() 

to.Text = ""; 
sub.Text = ""; 
message.Text = ""; 


protected void btn_Click(object sender, EventArgs e) 

try 

MailMessage mail = new MailMessage(); 
mail.To.Add(to.Text); 
mail.From = new MailAddress("sandeepraturi@gmail.com"); 
mail.Body = message.Text; 
mail.Subject = sub.Text; 
mail.IsBodyHtml = true; 
SmtpClient smtp = new SmtpClient(); 
smtp.Host = "smtp.gmail.com"; 
smtp.Credentials = new System.Net.NetworkCredential 
("sandeepraturi@gmail.com", "*********"); 
smtp.EnableSsl = true; 
smtp.Send(mail); 
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "ok();", true); 

catch 

Response.Write("write correct email id"); 


clear(); 
}

Sunday, 2 February 2014

Simple code for Select Multiple Value from Cheakbox List and save into Database


Database

id = int(auto increment,primary key) 
chk = varchar(50) 


Put this code in body tag 

<body> 
<form id="form1" runat="server"> 
<div align="center"> 
<h1 align="center">Select Name</h1> 
<asp:CheckBoxList ID="Chk" runat="server"> 
<asp:ListItem>Sandeep</asp:ListItem> 
<asp:ListItem>Dinesh</asp:ListItem> 
<asp:ListItem>Pradeep</asp:ListItem> 
<asp:ListItem>Kuldeep</asp:ListItem> 
</asp:CheckBoxList> 
<asp:Button ID="btn" runat="server" Text="submit" onclick="btn_Click" /></div> 
</form> 
</body> 

c# code


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; 

namespace sandeep 

public partial class WebForm2 : System.Web.UI.Page 

SqlConnection con = new SqlConnection("server=SANDEEP-PC;Database=data;Integrated Security=True"); 
protected void Page_Load(object sender, EventArgs e) 

if (IsPostBack != true) 





protected void btn_Click(object sender, EventArgs e) 

string str = string.Empty; 

for (int k = 0; k < Chk.Items.Count; k++) 

if (Chk.Items[k].Selected == true) 

str = str + Chk.Items[i].Text + ","; 



con.Open(); 
SqlCommand cmd = new SqlCommand(" insert into chk values ('" +str+ "') " , con); 
cmd.ExecuteNonQuery(); 
con.Close(); 






}

How we will use THEME in Asp.net


Note: 

1. Firstly add one skin file in your project 

put this code inside of skinfile form (skinfile.skin)


<asp:Label runat="server" BackColor="Yellow" ></asp:Label> 
<asp:TextBox runat="server" ForeColor="Black" BackColor="Yellow"></asp:TextBox> 
<asp:Button runat="server" ForeColor="Black" BackColor="Red" /> 

put this code inside of new form


<body> 
<form id="form1" runat="server"> 
<div> 
<table> 
<tr><td> <asp:Label ID="name" runat="server" Text="Name" ></asp:Label></td><td><asp:TextBox ID="txtname" runat="server" ></asp:TextBox></td></tr> 
<tr><td> <asp:Label ID="fname" runat="server" Text="Father Name"></asp:Label></td><td><asp:TextBox ID="txtfname" runat="server"></asp:TextBox></td></tr> 
<tr><td> <asp:Label ID="add" runat="server" Text="Address"></asp:Label></td><td><asp:TextBox ID="txtadd" runat="server" TextMode="MultiLine"></asp:TextBox></td></tr> 
<tr><td></td><td><asp:Button ID="submit" runat="server" Text="Submit" /><asp:Button ID="cancel" runat="server" Text="Cancel" /></td></tr> 
</table> 

</div> 
</form> 
</body> 

Note: 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Theme.aspx.cs" Inherits="Theme" EnableTheming="true" Theme="SkinFile" %> 

Write following property in this form: 
1. Theme ="SkinFile" // this is theme name 
2. EnableTheming="true"

Use of Panel in Asp.Net

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Use of Panel</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:RadioButtonList ID="rd" runat="server" RepeatDirection="Horizontal" onselectedindexchanged="rd_SelectedIndexChanged" AutoPostBack="true" >
<asp:ListItem>Student</asp:ListItem>
<asp:ListItem>Employee</asp:ListItem>
</asp:RadioButtonList>

<asp:Panel ID="p1" runat="server">
<table cellpadding="1" cellspacing="2">
<tr><td>Name</td><td><asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td></tr>
<tr><td>Address</td><td><asp:TextBox ID="TextBox2" runat="server"></asp:TextBox></td></tr>
<tr><td>Qualification</td><td><asp:TextBox ID="TextBox4" runat="server"></asp:TextBox></td></tr>
<tr><td>Email</td><td><asp:TextBox ID="TextBox3" runat="server"></asp:TextBox></td></tr>
</table>
</asp:Panel>

<asp:Panel ID="p2" runat="server">
<table cellpadding="1" cellspacing="2">
<tr><td>Emp Name</td><td><asp:TextBox ID="TextBox5" runat="server"></asp:TextBox></td></tr>
<tr><td>Address</td><td><asp:TextBox ID="TextBox6" runat="server"></asp:TextBox></td></tr>
<tr><td>Previous Job</td><td><asp:TextBox ID="TextBox7" runat="server"></asp:TextBox></td></tr>
<tr><td>Salary</td><td><asp:TextBox ID="TextBox8" runat="server"></asp:TextBox></td></tr>
</table>
</asp:Panel>


</div>
</form>
</body>
</html>

 C# Code 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class panel : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
p1.Visible = false;
p2.Visible = false;
}
protected void rd_SelectedIndexChanged(object sender, EventArgs e)
{

if (rd.SelectedItem.Text == "Student")
p1.Visible = true;


if (rd.SelectedItem.Text == "Employee")
p2.Visible = true;
}
}

Watermark on TextBox

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Validation in Asp.net</title>

<script type="text/javascript" language="javascript">
<!--
function doClear(theText) {
if (theText.value == theText.defaultValue) {
theText.value = ""
}
}

function doClear1(theText) {
if (theText.value == "") {
theText.value = theText.defaultValue
}
}
//-->
</script>

</head>
<body>
<form id="form1" runat="server">
<table cellpadding="0" cellspacing="0">
<tr>
<td >Full Name<span style="color:#DA251C">*</span></td>

<td><asp:TextBox ID="TextBox1" runat="server" MaxLength="25" Text="Enter Name" onFocus="doClear(this)" onblur="doClear1(this)"></asp:TextBox>&nbsp;&nbsp;
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Required" ForeColor="#DA251C" ControlToValidate="TextBox1" Display="Dynamic" CssClass="validation" ></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator4" runat="server" ControlToValidate="TextBox1" ValidationExpression="^[a-z A-Z]*$" ErrorMessage="Invalid Name" ForeColor="#DA251C" CssClass="validation" Display="dynamic"></asp:RegularExpressionValidator>
</td>

</tr>
<tr>
<td >Contact no<span style="color:#DA251C">*</span></td>

<td><asp:TextBox ID="TextBox5" runat="server" MaxLength="10" Text="Enter Contact" onFocus="doClear(this)" onblur="doClear1(this)" ></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Required" ForeColor="#DA251C" ControlToValidate="TextBox5" Display="dynamic" CssClass="validation" ></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="rg" runat="server" ControlToValidate="TextBox5" ValidationExpression="^[0-9]{10}$" ErrorMessage=" Invalid No." ForeColor="#DA251C" Display="Dynamic" CssClass="validation" ></asp:RegularExpressionValidator>
</td>

</tr>
<tr>
<td >E-mail <span style="color:#DA251C">*</span></td>

<td><asp:TextBox ID="TextBox6" runat="server" MaxLength="25" Text="Enter Email" onFocus="doClear(this)" onblur="doClear1(this)"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ErrorMessage="Required" ForeColor="#DA251C" ControlToValidate="TextBox6" Display="Dynamic" CssClass="validation" ></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Invalid E-mail" ForeColor="#DA251C" ControlToValidate="TextBox6" ValidationExpression="^[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|0-9]+([_][a-z|0-9]+)*)?@[a-z][a-z|0-9|]*\.([a-z][a-z|0-9]*(\.[a-z][a-z|0-9]*)?)$" CssClass="validation" ></asp:RegularExpressionValidator>
</td>

</tr>

<tr><td colspan="2"><asp:Button ID="btn" runat="server" Text="Submit" /></td></tr>

</table>
</form>
</body>
</html>