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.



Tuesday 9 August 2016

How to Debugging in SQL with Stored Procedure and Parameter

Debugging in SQL: 


Step 1 :- Create one table for testing, Here we have one table tbl_Players .


Step 2 :- Create one stored procedure with some parameter.


Procedure Script :

Create proc Sp_player
@id int,
@belongsTo varchar(50)
as

begin
select * from tbl_Players where PlayerID=@id and BelongsTo=@belongsTo 
end

Step 3:- Open new query window, and write below query with stored procedure name and parameter.

Here we are passing two parameter in stored procedure,  Id & belongsTo

            exec Sp_player 1,'India'

In above query 1 is first parameter value and India is second parameter value.


Now put breakpoint(Press F9) before  exec Sp_player 1,'India' ,  see above image for reference.

Step 4:- Now Press F11 to start debugging mode. After Press F11 you will see below window .

Step 5:- Now Press F10 for step by step debugging. And at the end of execution they will return output .


In simple way :
  • Write storedprocedure name with parameter  :-   exec Sp_player 1,'India'
  • Put Breakpoint(Press F9)     
  • Press F11 to start debugging mode in SQL
  • Press F10 for Step by Step debugging
  • Return debugging Result



Monday 8 August 2016

How to Start, Stop or Pause SQL Services

Here, i am going to write how we will start and stop SQL server services

Steps are :

  • Press Window + R
  • Type  services.msc  > Ok


select SQL Server and take action according your need, see below image for Reference.





Sunday 7 August 2016

How we will Update Existing Entity Data Model in MVC5

Why you need to update Data Entity Model??

Suppose you added few new column in your tables. And if you want to show them in your MVC Application Class then you need to Update Entity data Model. If you will not update Entity Model,  new columns will not reflect there.

How to Update Data Entity Model ?? 

Double Click on Entity data model, see below image


Right Click on Entity Model Page > Update Model From Databse

Then Goto Refresh> Select Table > Finish


Now new column will reflect automatically in your class.


Simple CRUD( Create, Read, Update or Delete) Operation with MVC5 Using Entity Data Model

MVC CRUD Operation using Entity Data Model or Database First Approach

CRUD : - Create, Read/Retrieve, Update and Delete or you can say Insert, Update, Select and Delete

So let's start with quick revision!

Model : Model is responsible for maintaining the data, here we write data access logics,
business access logics & we also maintain the Validations in model

View : View is responsible for displaying the data.

Controller : Controller is Responsible for any new request which has comes by user.  Controller identify the request and send to them relevant action.

Steps are

  • Open Visual studio 2015
  • Go to file  >  New  > Project  



  • Select ASP.Net Web Application
  • Give Name to Application > ok















Now solution has been created successfully.

Before starting, create tables in sql. Use below query for create table.

CREATE TABLE [dbo].[RegistrationDetails]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
[MobileNo] [varchar](50) NULL,
[EmailID] [varchar](50) NULL,
[Age] [varchar](10) NULL,
[Address] [varchar](50) NULL,
 CONSTRAINT [PK_RegistrationDetails] PRIMARY KEY CLUSTERED 
(
[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO


Now we will create Connection with Entity Data Model:

Steps are :

Right click on Model Folder > Add > New Item > In Left Pane  select Data > ADO.Net Entity Data Model> Give Name( Model1)> Add

select  EF Designer from Database > Next > New Connection >



How to Know about your SQL Server name?? dont worry it is very easy to find out.
Let's see..

Open Sql Server > Right Click on Left Icon see below image > Properties





Copy server name  and paste into place of server name, see below image for ref.

Paste server name > Select database name > Ok






Here dataEntities is your connection name , click on next.
Now, we will select table name which we want to use, like our table name is RegistrationDetails


Select table Name, see below image 


select table name and then click on finish.


Note :  In MVC, we works with object and class.  Model converts our table into class and table column  name  into Properties.  see below image for Ref .



Now connection has been created successfully.


Now we will create Controller  

In Controller we will write Action for each request like Insert, update, delete...

Steps are  :
  • Right click on Controller Folder
  • Add > Controller >  MVC 5 Controller - Empty > Add








Give name to controller like above image Registration.
Note :
In above screenshot highlighted text controller comes by default so don't remove it, its represents Registration is Controller, so don't remove it other it will not work.

After Adding Controller 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace sandeepcodes.Controllers
{
    public class RegistrationController : Controller
    {
        // GET: Registration
        public ActionResult Index()
        {
            return View();
        }
    }
}

Now we will Create Action for Insert and View page for Insert


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace sandeepcodes.Controllers
{
    public class RegistrationController : Controller
    {
        // GET: Registration
        public ActionResult Index()
        {
            return View();
        }

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

    }

}

Now how to add view for Insert Action :

Right click on Action > Add View > View name should be same as Action name, don't change it.
See below screenshot for ref  :-



Note :

When we add controller then automatically one folder has created inside of View Folder same name as Controller name. It represents this is controller view folder. 

How to find out your View??

Goto view folder> Registration Folder> Your view(Insert), see below screen shot


Open your view page Click on Insert.cshtml

and write below code


@model sandeepcodes.Models.RegistrationDetail
@{
    ViewBag.Title = "Registration Form";
}
<h2>Insert</h2>

@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" })
            
        </div>

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

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

        </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 :
Add below line code into your view page, here we gives path of our class RegistrationDetail to view with the help of this view will inherit the class fileds.

@model sandeepcodes.Models.RegistrationDetail

In above code  : -  sandeepcodes is my solution name and RegistrationDetail is my Class name which is inside of Model Folder

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

In above code we are going to submit data that's why we are using Form Method is Post
Insert : - Insert is Action name on Controller Page
Registration : - Registration in Controller name
 ( So change name according to you code which you write)

Now Run Your Application :-

Open View Page Insert.cshtml and Click on Run command, view will look like :-


Now Display part has been ready now we will work on Submit Data, so go to Controller and we will create Post Properties for Insert Action.

Note 

We are going to submit data into database now we need to connection file name, so add reference of connection file

using sandeepcodes.Models;//  Add ref of Model

Create object of Connection File 

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

See code below : -

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

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)
        {
   
                db.RegistrationDetails.Add(obj);
                db.SaveChanges();  
                return RedirectToAction("Insert", "Registration");
        }

    }


}


In above code we create new Post Action(Insert) with same name as Get action (Insert). By default Action has Get Property.
  public ActionResult Insert(RegistrationDetail obj)  :  Here RegistrationDetails is class name .

Build Your Solution and Run the application.

Output of My submission form :




Now How we will Read Data/ Bind Data or you can say display data in MVC??


Dont worry, it is very easy.  Let's follow the below steps :-


Now we will Add Action for Read/ Show/ Details

Add Details() Action in Registration Controller


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

Here we will use .ToList() to show all records in List Format.
We are going to show data from database so we don't need to write [HttpGet] method, because by default Action has Get.

Now we will create view for Details Action

Follow same steps like Insert Action...

Right Click on Details() Action > Add View

View Name should be same as Action Name.

Now open Details.cshtml view page and write below code

@using sandeepcodes.Models
    @{
        ViewBag.Title = "Details";
    }

    <h2>Details</h2>


    <div>

        <table class="table table-striped table-hover" style="width:800px; border:1px solid #cdcdcd">
            <tr>
                <td>Name</td>
                <td>MobileNo</td>
                <td>Address</td>
                <td>Age</td>
                <td>Email</td>
            </tr>
             @foreach (RegistrationDetail item in Model)
             {
                <tr>
                    <td width="100px">@item.Name</td>
                    <td>@item.MobileNo</td>
                    <td>@item.Address</td>
                    <td>@item.Age</td>
                    <td>@item.EmailID</td>
                </tr>
             }


    </table>

</div>

Note : 

  •  we are using foreach loop to bind data in table, for loop execute till last record.


  • @using sandeepcodes.Models :- Here  we are giving path of Registration class, because registration class is inside of Model Folder & Sandeepcodes is my solution name .


Build your solution & Run the application.

Output  : -

Now How we will Select Records in MVC?? 

we will add one Edit link in Details page, Open Details.cshtml view page and write below code.

Add this code inside of For loop

                     <td>
                        @Html.ActionLink("EditData", "Edit", new { id = item.ID})
                    </td>



Complete view code are :

@using sandeepcodes.Models
    @{
        ViewBag.Title = "Details";
    }

    <h2>Details</h2>

    <div>
        <table class="table table-striped table-hover" style="width:800px; border:1px solid #cdcdcd">
            <tr>
                <td>Name</td>
                <td>MobileNo</td>
                <td>Address</td>
                <td>Age</td>
                <td>Email</td>
                <td></td>
            </tr>
             @foreach (RegistrationDetail item in Model)
             {
                <tr>
                    <td width="100px">@item.Name</td>
                    <td>@item.MobileNo</td>
                    <td>@item.Address</td>
                    <td>@item.Age</td>
                    <td>@item.EmailID</td>
                 
                    <td>

                        @Html.ActionLink("EditData", "Edit", new { id = item.ID})
                    </td>

                </tr>
             }


    </table>

</div>

Now we will add Action for Edit 

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


Now execute you Details.cshtml view page and click on any edit link,  Records will show you on Edit view page.



Now we are going to Update select Records in MVC


Add below action for this and here we will use Post method because we are going to update details means submit to data into database.

let's have a look

Namespace are  

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;

Action :- 

  [HttpPost]
        public ActionResult Edit(RegistrationDetail obj)
        {
            RegistrationDetail data = db.RegistrationDetails.Find(obj.ID);
            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");

        }

 Build your application and execute Details.cshtml view page and select any record and update them.

How to Delete Record in MVC ??
Add on Delete link in Details.cshtml view page like Edit Link

  @Html.ActionLink("Delete", "Delete", new { id = item.ID })

Action for Delete

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

        }

Build your application & execute Details.cshtml page

See below image before delete record




After delete record 


Now Complete Controller Code are  :

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)
        {
   
                db.RegistrationDetails.Add(obj);
                db.SaveChanges();  
                return RedirectToAction("Insert", "Registration");
        }

        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");
        }

    }


}

All operation has been completed, hope you will be enjoy it.

Give your feedback to improve the article.