April 2016 ~ MiTechDev.com

Mitechdev.com is a programming blog which focused on Web Programming and development

Saturday, 30 April 2016

HTML Option Group support Dropdownlist in MVC 5

05:51:00 Posted by raviteja swayampu No comments

Hello every one welcome again.Thank you all for your response for previous post.To day post i am going to explain "How to implement option Group support DropdownList in ASP.NET MVC application.
Description: In HTML "optgroup " tag groups related options in Drop down list.The Grouping of options is helpful when you have more options and group of options in drop down list.
In HTML markup we implement option group drop down list like this,
Example:
<!DOCTYPE html>
<html>
<body>
<select>
  <optgroup label="Mens Clothing">
    <option value="T-shirts">T-shirts</option>
    <option value="TrackSuit">Track Suit</option>
  </optgroup>
  <optgroup label="Mens Footwear">
    <option value="Shoes">Shoes</option>
    <option value="Sandals">Sandals</option>
  </optgroup>
</select>  
</body>
</html>

The Drop down like this



Now we are going to do the same dropdown list using ASP.NET MVC .
Step 1: 
Create an MVC web application.
1.Open Visual studio 2013.
2.Goto File menu-->New-->Project.
3.Select "ASP.NET web template" from installed templates.
4.Name the project and select  location.
5.Select Empty MVC template.
5.Select MVC checkbox to add MVC folder structure.

HTML-option-group-dropdownlist-in-MVC5

Step 2: 
Prepare a Model in Models folder
1.Create DropdownModel.cs
2. Replace code with following code.
DropdownModel.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcApplication5.Models
{
    //dropdown data
    public class DropdownModel
    {
        public List DropdownDataModel { get; set; }
        public List ParentDataModel { get; set; }
        public List ClildDataModel { get; set; }
        public int SelectedValue { get; set; }
    }
    //Parent values
    public class Parent
    {
        public int ParentId { get; set; }
        public string ParentName { get; set; }
    }
    //Child values
    public class Clild
    {
        public int ParentId { get; set; }
        public int ChildId { get; set; }
        public string ChildName { get; set; }
    }
}

Step 3:
Create Controller
1.Right click on Controllers folder-->Add-->Controller
2.Name it as HomeController.cs (For demo purpose).
step 4:
Prepare the Data source for Drop down list in Controller.
Note: In this tutorial i created data source in Controller but in real time we use Data Access Layers for getting Database data.
1.I prepared the data source for dropdownlist in Controller.
HomeController.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication5.Models
{
    public class HomeController : Controller
    {
        //Index method to render Index page.
        public ActionResult Index()
        {
            DropdownModel objdropdownmodel = new DropdownModel();
            objdropdownmodel.ParentDataModel = new List();
            //Get Parent options of Dropdownlist using GetParentData()
            objdropdownmodel.ParentDataModel = GetParentData();
            objdropdownmodel.ClildDataModel = new List();
            //Get Child options of Dropdownlist using GetClildData()()
            objdropdownmodel.ClildDataModel = GetClildData();
            //Sending DropDownList data using View() method
            return View(objdropdownmodel);
        }
        //post method to receive the drop down data 
        //you can save it in db also.
        [HttpPost]
        public ActionResult Index(int TeavelMode)
        {
            DropdownModel objdropdownmodel = new DropdownModel();
            objdropdownmodel.ParentDataModel = new List();
            objdropdownmodel.ParentDataModel = GetParentData();
            objdropdownmodel.ClildDataModel = new List();
            objdropdownmodel.ClildDataModel = GetClildData();
            objdropdownmodel.SelectedValue = TeavelMode;
            ViewBag.SelectedValue = "Selected Value :" + objdropdownmodel.ClildDataModel.Where(m => m.ChildId == TeavelMode).FirstOrDefault().ChildName;
            return View(objdropdownmodel);
        }
        //You can use DB to access data for this section
        //Parent options data source
        public List GetParentData()
        {
            List objparent = new List();
            objparent.Add(new Parent { ParentId = 1, ParentName = "--Car--" });
            objparent.Add(new Parent { ParentId = 2, ParentName = "--Bike--" });
            return objparent;
        }
        // You can use DB to access the data
        //Child options data source
        public List GetClildData()
        {
            List objchild = new List();
            objchild.Add(new Clild { ParentId = 1, ChildId = 1, ChildName = "Honda City" });
            objchild.Add(new Clild { ParentId = 1, ChildId = 2, ChildName = "Vento Polo" });
            objchild.Add(new Clild { ParentId = 1, ChildId = 3, ChildName = "Audy" });
            objchild.Add(new Clild { ParentId = 1, ChildId = 4, ChildName = "Honda Amaze" });
            objchild.Add(new Clild { ParentId = 2, ChildId = 5, ChildName = "CBR 250" });
            objchild.Add(new Clild { ParentId = 2, ChildId = 6, ChildName = "CBR 150" });
            objchild.Add(new Clild { ParentId = 2, ChildId = 6, ChildName = "Pulsar 200" });
            objchild.Add(new Clild { ParentId = 2, ChildId = 8, ChildName = "Bajaj Discover 125" });
            return objchild;
        }
    }
}

Step 5:
Create UI for Drop down list in Index View
1.Right click Index Action-->Add View.
2.In Add View window wizard click Add button.
3.Replace the Index code with following code.

@model MvcApplication5.Models.DropdownModel
@{
    ViewBag.Title = "Display DropdDownList Item By Group in Asp.Net MVC Using C#.Net";
}
@using (Html.BeginForm("Index", "Home"))
{
    <div>
        Trevel Mode:
        <select name="TeavelMode" id="ddltravelmode">
            <option value="0">Select</option>
            @*Iterates the data to display drop down*@
            @foreach (var pitem in Model.ParentDataModel)
            {
                <optgroup label="@pitem.ParentName">
                    @{
                            var childitemfilter = Model.ClildDataModel.Where(m => m.ParentId == pitem.ParentId);
                            if (childitemfilter != null)
                            {
                                foreach (var citem in childitemfilter)
                                {
                                    string selectedValue = "";
                                    if (Model.SelectedValue == citem.ChildId)
                                    {
                                        selectedValue = "selected='selected'";
                                    }
                                   
                        <option value="@citem.ChildId" @selectedValue>@citem.ChildName</option>
                                }
                            }
                    }
                </optgroup>
            }
        </select>
        <input type="submit" value="Submit" />
    </div>
    <div>
    </div>
    //Displays selected value after clicking submit button
    <div style="font-weight:bold">@ViewBag.SelectedValue</div>
}
Now Run the application Press F5.
we will get  Option Group Drop down list like this.


HTML-option-group-dropdownlist-in-MVC5

The selected Value will be displayed like below.

HTML-option-group-dropdownlist-in-MVC5
Download the code from this link....Download
Conclusion:
I hope you all understand my tutorial .if you recommend any modifications please suggest me.


Thursday, 28 April 2016

Multi Select Dropdown in MVC 5

08:09:00 Posted by raviteja swayampu 3 comments
Don't you know how to create multi select drop down list in MVC 5.It is very easy in traditional HTML and ASP.NET webform. But when comes to the MVC it is a little bit difficult.But, binding database values to the dropdown list very easy in MVC compared to HTML.
In normal dropdown list we can allow to select single option from drop down but using multi select list box we can able to select multiple options.

In this tutorial i am going to share you how to populate multi select drop down List  in mvc by comparing normal dropdown list.

Step 1: create an ASP.NET MVC web application
1.Add Controller name it as HomeController.cs
2.Create action method Index()
Step 2: create data source for drop down list
1.create List data to populate a drop down.
2.Replace Index action with following code.
public ActionResult Index()
        {
            //Using ViewBag
            List item=new List();
            item.Add(new SelectListItem{Text="India",Value="India"});
            item.Add(new SelectListItem{Text="China",Value="china"});
            item.Add(new SelectListItem { Text = "United Sates", Value = "3" });
            item.Add(new SelectListItem { Text = "Srilanka", Value = "4" });
            item.Add(new SelectListItem { Text = "Germany", Value = "5" });
            item.Add(new SelectListItem { Text = "Japan", Value = "6" });
            item.Add(new SelectListItem { Text = "Nepal", Value = "7" });
            item.Add(new SelectListItem { Text = "Russia", Value = "8" });
            item.Add(new SelectListItem { Text = "Spain", Value = "9" });
            item.Add(new SelectListItem { Text = "Frans", Value = "10" });
            item.Add(new SelectListItem { Text = "Canada", Value = "11" });
            item.Add(new SelectListItem { Text = "brazil", Value = "12" });
            item.Add(new SelectListItem { Text = "Koria", Value = "13" });
            item.Add(new SelectListItem { Text = "England", Value = "14" });
            //using ViewData
            //Data for drop down list
            ViewBag.countrylist = item;   
            //data sent for multiselect dropdown.
            ViewBag.MultiselectCountry = GetCountries(null);
            return View();
        }

Step 3:Prepare data for multi select listbox
1.Here i created a GetCountries() method with type as 'MultiSelectList'.
2.Data for Multi select drop down List box comes from here.

 private MultiSelectList GetCountries(string[] SelectedValues)
        {
            List items = new List();
            items.Add(new SelectListItem { Text = "India", Value = "1" });
            items.Add(new SelectListItem { Text = "China", Value = "2" });
            items.Add(new SelectListItem { Text = "United Sates", Value = "3" });
            items.Add(new SelectListItem { Text = "Srilanka", Value = "4" });
            items.Add(new SelectListItem { Text = "Germany", Value = "5" });
            items.Add(new SelectListItem { Text = "Japan", Value = "6" });
            items.Add(new SelectListItem { Text = "Nepal", Value = "7" });
            items.Add(new SelectListItem { Text = "Russia", Value = "8" });
            items.Add(new SelectListItem { Text = "Spain", Value = "9" });
            items.Add(new SelectListItem { Text = "Frans", Value = "10" });
            items.Add(new SelectListItem { Text = "Canada", Value = "11" });
            items.Add(new SelectListItem { Text = "brazil", Value = "12" });
            items.Add(new SelectListItem { Text = "Koria", Value = "13" });
            items.Add(new SelectListItem { Text = "England", Value = "14" });
            return new MultiSelectList(items, "Value", "Text", SelectedValues);
        }

3.I passed this data using ViewBag to Index view in Index Action Method.You can see the code in first code snippet.

Step 4:Create Index View
1.Right click on Index action -->Add View-->click ok
2.Index view created .
3.Replace the Index view code with following code

@{
    ViewBag.Title = "Multiselect List box";
}
<link href="~/Content/Bootstrap.min.css" rel="stylesheet" />
<h2 style="margin-top:60px;">Chosen Js plugin</h2>
@using (Html.BeginForm()) { 
@Html.Label("1. Single select")<br/>    
@Html.DropDownList("countrylist",null,"select single country",new { style="width:200px;"})<br/><br/>
@Html.Label("2.Choosen Multiple select")<br/>       
@Html.ListBox("multiselectcountries", ViewBag.MultiselectCountry as MultiSelectList, new { style = "width:200px;" })<br/><br/>    
}

Now run the application and see browser window.
we can select multiple values by pressing CTRL select.


download this code for this article from here.

Conclusion:
 I hope every reader understand this tutorial.If you recommend any modification please let me know to increase the readability of this article.


Monday, 25 April 2016

Sweet Alert in MVC5

22:53:00 Posted by raviteja swayampu , 1 comment
sweet alert in mvc
Sweet Alert:
Sweet alert is a beautiful replacement for java script alert message box.It adds styles to the alert messages make alert look great.And also we can customize the alert with custom icons and custom styles etc.It is more user friendly and user experience very good.All this can be achieved by less code.
The following is normal java script alert in browser.

it looks normal to us.But sweet alert look like below with customizable styles.


That's why we in many of the websites to drag the user attention many of developers use this sweet alert.Now i am going to teach you how to integrate this sweet alert in out MVC application.

Sweet Alert in MVC 5

As like previous i going to explain this in step by step manner.
Step 1:

Create MVC application

1.Open Visual studio.
2.Goto File Menu-->New-->Project-->Select ASP.NET Webproject.
3.Give name as SweetAlertExample and click ok button.

creating-new-project-in-mvc5

4.In after clicking on Ok button another project wizard will opened like below.Select Empty template and check the MVC checkbox to add the default folders for MVC application.And click ok to add those to project.


Step 2:

Create a Controller


1.Right click Controllers folder-->Add-->Controller and name it as HomeController.cs

2.Right click on Index Action method and add Index View and click on Add.


Step 3:

Installing Sweet Alert in MVC

We can install sweet alert in mvc application in two ways
    Using package manager console:
    Goto Menubar-->Tools-->Nuget Package Manager-->Package Manager Console.And use                     following command to install Sweet alert.
     Install-Package SweetAlert
      folder structure look like below
 
    By downlading and adding folder to the project:
    You can directly add folders to the solution by downlaoding from following link.

Note : Add Bootstrap to project using either nuget package manager or using CDN.
Step 4:
Replace Index view code with below code.
@{
    ViewBag.Title = "Sweet Alert Example";
}
<script src="http://tristanedwards.me/u/SweetAlert//lib/sweet-alert.js"></script>
<link rel="stylesheet" type="text/css" href="http://tristanedwards.me/u/SweetAlert//lib/sweet-alert.css">
<link href="~/Content/Bootstrap.min.css" rel="stylesheet" />
 <div class="wrapper panel panel-primary" >
            <div class="panel-heading">Sweet Alert Demonstration</div>
        <div class="panel-body">
            <p>It makes sweet alerts!</p>
            <p>Default icons got a little goofy, but whatever....</p>
            <p>
                <button id="test-1" class="btn btn-info btn-lg">Basic</button>
                <button id="test-2" class="btn btn-success btn-lg">Success</button>
                <button id="test-3" class="btn btn-primary btn-lg">Fancy</button>
                <button id="test-4" class="btn btn-danger btn-lg">Error</button>
            <p><a class="btn btn-link" href="http://www.mitechdev.com" target="blank">http://www.mitechdev.com</a>

            <p>&nbsp;</p>
        </div>
</div>
Step 5: 
Add following Script to Index page
 document.querySelector('#test-1').onclick = function () {
        swal("Here's a message!");
    };
    document.querySelector('#test-2').onclick = function () {
        swal("Good job!", "You clicked the button!", "success")
    };
    document.querySelector('button#test-3').onclick = function () {
        swal({
            title: "Are you sure?",
            text: "Your will not be able to recover this imaginary file!",
            type: "warning",
            showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "Yes, delete it!"
        });
    };
    document.querySelector('button#test-4').onclick = function () {
        swal("Oops...", "Something went wrong!", "error");
    };

1.Also add styles in index page

.wrapper {
        height: 300px;
        width: 500px;
        margin-top: 150px;
        margin-left: 350px;
        text-align:center;
    }

Finally run the application Press F5.


A sample Success alert will come like this...


Download source code from here Download.

Conclusion:
I hope this article is understandable for every reader.If you recommend any modifications please let me know to improve the user readability.


Sunday, 24 April 2016

How to add CKEDITOR in MVC 5

21:49:00 Posted by raviteja swayampu 1 comment
Do you know how to integrate CKEDITOR to ASP.NET MVC application.In this article i am going to tell you how to add CKEDITOR to MVC 5 application.

What is CKEDITOR:

  Ckeditor is a ready for use HTML text editor designed to simplify the web content creation.It's a         WYSIWYG editor that brings common word processor features directly to your web pages.                 Enhance your website experience with our community maintained editor.
  Features of Ckeditor:
  1. open source
  2. Community Driven
  3. Fully Customizable
  4. Enriches website experience
  5. High standard of quality
  6. Free.
  7. Compatibility with different browsers.

How to add CKeditor to MVC 5 application:

Step 1: Create MVC 5 application.
1.Open Visual studio 2013 or 2015-->File Menu-->New-->Project.
2.Select ASP.NET web application template-->choose Empty in new project window-->Check MVC checkbox-->click Add button.
3.Visual studio adds default folders to the mvc 5 application.

Step 2: Download Ckeditor form here Download ckeditor.
1.Extract the downloaded folder.
2.copy folder in visual studio solution.


3.I added Ckeditor folder in Scripts folder.

Step 3: Add reference to ckeditor files in _Layout.cshtml page and remove all other references.
<script src="~/Scripts/jquery-1.10.2.js"></script>
    <script src="~/Scripts/ckeditor/ckeditor.js"></script>
    <link href="~/Content/Bootstrap.min.css" rel="stylesheet" />
Step 4: Add Controller and Views
1.Right click controllers folder-->Add-->Controller-->Select Empty Controller-->name it as HomeController.cs-->click ok.
2.Right click Index action method-->Add View-->click ok.
3.Replace Index view with following code.
<title>A Simple Page with CKEditor</title>
@using (Html.BeginForm("ckeditor", "Home", FormMethod.Post, new { style="margin-top:100px;"}))
{ 
    @Html.Label("The Badboy Web Editor")<br/>
    @Html.TextArea("editorplace", new { @id = "editor1" })
        <input type="submit" value="Submit" id="btnSubmit"/>
        <script>
            // Replace the <textarea id="editor1"> with a CKEditor
            // instance, using default configuration.
            CKEDITOR.replace('editor1');
        </script>
}
Note: Here Textarea id value must be replaced with Ckeditor using replce() method as shown in script tag.


Here we are replacing the Text area by Ckeditor. So,Texta area contains all data of Ckeditor. We can save the data of textarea using model binding or also we can send ckeditor data using jquery ajax method based on the textarea "id & name" values.
Download source from here Downlaod.
Conclusion :
I hope this article useful to every reader.i will  meet you in another tutorial.

Wednesday, 20 April 2016

Jquery Tooltip validation Using Twitter Bootstrap in MVC 5

05:22:00 Posted by raviteja swayampu , 1 comment
Hello every one welcome again.I hope my last post "file upload using Ajax" helped you a lot.There are more programming examples and sample code are avilable in this site.I am always want to share my knowledge. Because, by sharing knowledge i can able to more.
In this article i am gonna teach you "Jquery tooltip valiadation using twitter bootstrap".Generally we use "Jquery unobtrusive validation plugin" in ASP.NET MVC applications.
Topics we are going to discuss in this article:
1.Disadvantages of Jquery unebtrusive validation in MVC.
2.Jquery tooltip validation

There are some disadvantage of using this plugin.When using Jquery unobtrusive validation plugin it creates a span tag to dispplay error messages.If you have, for example, a horizontal form on top of other controls then this behavior might not be working for you since they will break the page layout. It was the case for me and as such I decided to change the default behavior of the JQuery unobtrusive validation library and instead of using a span to show the error message I decided to use a tooltip.I am going to show you how i acheived this using a tooltip with help of bootstrap.

Before going to tooltip validation first look at the traditional jquery unobtrusive example..
The following is a example application of unobtrusive validation.

jquery-tooltip-validation-using-bootstrap-in-mvc5

when i click on Register button then error messages look like this

jquery-tooltip-validation-using-bootstrap-in-mvc5
If i increases the length of error message the layout will be breaked like this.In the same way when i place the same lengthy error message below the Textbox controls insted of beside the controls as shown in screenshot same layout change problem occurs.So,This is a bad idea of using default behaviour of Jquery Unebtrusive validation plugin.I replaced the error type with tooltip.it won't chage the layout structure.
Now Jquery tooltip validation article begins from here,

Jquery tooltip validation using Twitter Bootstrap

Step 1: Create a ASP.NET MVC application
1. create a application with MVC template.

jquery-tooltip-validation-using-bootstrap-in-mvc5

2.Add following files to the solution

jquery-tooltip-validation-using-bootstrap-in-mvc5

3.create HomeController.cs:
   a.right click-->Controllers folder-->Add-->Controller-->Name it as HomeController.cs.

jquery-tooltip-validation-using-bootstrap-in-mvc5

4.Add Index Method to controller.
5.Add View to Index Action method
   a.Right click-->Index Method-->Add View-->Click Ok.

jquery-tooltip-validation-using-bootstrap-in-mvc5

   b.Index view created.

6.Now replace the code Index.cshtml code with below code.
<!DOCTYPE html>
<html>
<head>
    <title>Bootstrap tooltip Example</title>

    <!-----------------resource files------------->
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-1.9.1.min.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery-validate.bootstrap-tooltip.min.js"></script>
    <script src="~/Scripts/myscript.js"></script>

</head>
<body>
<div id="main">
    @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { name = "RegistrationForm", id = "RegistrationForm" }))
    {
        <fieldset style="padding-left: 100px; box-shadow: 2px 2px 2px 2px #000;margin-top:30px;height:500px;">
            <legend style="font-size:larger;font-weight:bold;">Registration page</legend>
            <div id="left-part" align="left" style="float:left;margin-left:20px;">
                @Html.Label("FirstName", new { required = "required" })<br />
                @Html.TextBox("FirstName")<br /><br />
                @Html.Label("LastName")<br />
                @Html.TextBox("LastName")<br /><br />
                @Html.Label("UserName")<br />
                @Html.TextBox("UserName")<br /><br />
                @Html.Label("Gender")<br />
                @Html.RadioButton("Gender", "Male", false, new { id = "rbnMale", name = "rbnMale" })Male
                @Html.RadioButton("Gender", "Female", false, new { id = "rbnFemale", name = "rbnFemale" })Female
                <br /><br />
                @Html.Label("Email Id:")  <br />
                @Html.TextBox("Email", null, new { type = "email" })<br /><br />
            </div>
            <div id="right-side" style="margin-left:400px;">
                @Html.Label("Password")<br />
                @Html.Password("Password")<br /><br />
                @Html.Label("ConfirmPassword")<br />
                @Html.Password("ConfirmPassword")<br /><br />
                @Html.Label("MobileNo")<br />
                @Html.TextBox("MobileNo", null, new { type = "number" })<br /><br />
                @Html.Label("State")<br />
                @Html.TextBox("State")<br /><br />
                @Html.Label("Country")<br />
                @Html.DropDownList("CountryDropdownlst", new List<SelectListItem>()
                         {
                            new SelectListItem(){Text="India",Value="0"},
                            new SelectListItem(){Text="China",Value="1"},
                            new SelectListItem(){Text="USA",Value="2"},
                            new SelectListItem(){Text="Russia",Value="3"}
                         }, "--select--", new { id = "CountryDropdownlst" })
                <br /><br />
                <input type="submit" value="Register" id="btnSubmit" name="btnSubmit" class="btn btn-primary"/>
            </div>
        </fieldset>
    }
    <br />
</div>
</body>
</html>

Step 2: Add script for validation
1.Add myscript.js to the script folder..

myscript.js:

//if no errors form will be submited
$.validator.setDefaults({
    submitHandler: function () {
        alert("form submited!");
    }
});
debugger;
$(document).ready(function () {
    $("#RegistrationForm").validate({
        rules: {
            FirstName: {
                required: true,
                minlength: 4,
                maxlength: 15
            },
            LastName: {
                required: true,
                minlength: 4,
                maxlength: 15
            },
            UserName: {
                required: true,
                minlength: 5
            },
            Gender: { required: true },
            Email: {
                required: true,
                email: true
            },
            Password: {
                required: true,
                minlength: 5,
                maxlength: 20
            },
            ConfirmPassword:{
                required: true,
                equalTo:"#Password"
            },
            MobileNo: {
                required: true,
                number: true,
                minlength: 10,
                maxlength:12
            },
            State: { required: true ,minlength:5},
            CountryDropdownlst: {
                required:true
            }
        },
        messages: {
            Gender: "Pls Select the Gender!",
            FirstName: {
                required: "Firstname required Firstname required Firstname required Firstname required ",
                minlength: "pls enter min 4 chars",
                maxlength:"only 15 chars are allowed"
            },
            LastName: {
                required: "Lastname required",
                minlength: "pls enter min 4 chars",
                maxlength: "only 15 chars are allowed"
            },
            UserName: {
                required: "Username is mandatory",
                minlength:"pls enter min 5 chars"
            },
            Password: {
                required: "Password is mandatory",
                minlength:"pls enter min 5 chars"
            },
            ConfirmPassword: {
                required: "Pls confirm password",
                equalTo:"password does not match"
            },
            MobileNo: {
                required: "pls enter mobile no",
                minlength: "pls enter valid mobile no"
            },
            State:"Pls enter valid state",
            CountryDropdownlst:"pls select your country"

        },
        //tooltip options to change position of tooltip..
        tooltip_options: {
            FirstName: { trigger: 'focus' },
            Gender: { placement: 'top', html: true }    //placement:'bottom'for bottom
        },
        //submitHandler: function (form) {
        //    $("#validity_label").html('
No errors. Like a boss.
'); //}, invalidHandler: function (form, validator) { $("#validity_label").html('
There be ' + validator.numberOfInvalids() + ' error' + (validator.numberOfInvalids() > 1 ? 's' : '') + ' here. OH NOES!!!!!
'); } }); });

Step 3:
1.Add styles for error display.

 .tooltip{
            margin-left:100px;           
        }
        .tooltip-inner {
            background: #ff3333; /*tooltip text background color*/
            border-radius: 0px;
            font-weight: bolder;
            box-shadow: 1px 1px 1px 1px black;
        }
        .tooltip.top .tooltip-arrow {
            border-top-color: red;
            margin-left: -55px;           
        }
        input[type="text"],input[type="password"],input[type="number"],input[type="email"], #CountryDropdownlst {
            box-shadow: 1px 1px 1px 1px grey;
            width: 200px;
        }
        #CountryDropdownlst{
            height:27px;
        }
        /*.tooltip-inner tooltip-arrow {
            margin-left: 200px;
        }*/

Now run application you will get window like this..


jquery-tooltip-validation-using-bootstrap-in-mvc5
Without entering anything into fields just click on Register button button and see what happens.

jquery-tooltip-validation-using-bootstrap-in-mvc5
In above screen shot if i increases the length of error message layout does not change.
Downlaod source code Download.

Related Articles:

Conclusion:
I hope this article is understandable for every reader.It also helpful in real time projects.If you recommend any suggestion for improving this article i am always welcome.


Tuesday, 19 April 2016

File Upload Using Ajax

03:34:00 Posted by raviteja swayampu , 1 comment
Hello Every in this tutorial i am gonna teach you How to upload a file using Ajax without page refresh by using a  ajax file upload jquery Addon or plugn.These plugins increases the functionality of jquery.Before going in deep we need to know what is File Upload Plugin.
What is Jquery file upload plugin:
It is an ajax enabled jquery plugin for uploading,
  • Images(includes jpg,png,gif etc)
  • Documents,
  • PDF's,
and so on.........
It is very easy t o use..
we can upload multiple files at a time (i will discuss multiple file uploads later).
built-in validation rules.
these are the features of the jquery file upload plug in .
Now i will explain this by doing a sample file upload example in step by step manner.

Step 1:
1.Create a Mvc Application using Empty MVC template.
2.name it.

Step 2:
1.Add a Model class to the Model folder.
2.model.cs

public class MyModel
    {
        public HttpPostedFileBase file { get; set; }
    }

3.I added a property 'file' of type "HttpPostedFileBase" for Model binding.

Step 3:
1.Add a Controller for rendering View..
2.HomeController.cs

public ActionResult Index()
        {           
            return View();
        }
Step 4:
1.Before that add the libreary files of jquery and file upload plugin files.


2.Add reference this files in _Layout.cshtml page like below.


Step 5: 
1.Add controller for handling file uploads
2.name it as 'FileUpload'.
3.This method must be specified as [HttpPost] .Because it receives data from View page.
4.I also created a extra method for creating a directory for saving the uploaded files.(If you added a upload folder in Solution this method is not required).
FileController.cs:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace TestAjaxUpload
{
    public class FileController : Controller
    {
        [HttpPost]
        public  ActionResult UploadFile()
        {
            HttpPostedFileBase myFile = Request.Files["MyFile"];
            bool isUploaded = false;
            string message = "File upload failed";

            if (myFile != null && myFile.ContentLength != 0)
            {
                string pathForSaving = Server.MapPath("~/Uploads");
                if (this.CreateFolderIfNeeded(pathForSaving))
                {
                    try
                    {
                        myFile.SaveAs(Path.Combine(pathForSaving, myFile.FileName));
                        isUploaded = true;
                        message = "File uploaded successfully!";
                    }
                    catch (Exception ex)
                    {
                        message = string.Format("File upload failed: {0}", ex.Message);
                    }
                }
            }
            return Json(new { isUploaded = isUploaded, message = message }, "text/html");
        }
        //This method create a directory for saving files.
        private bool CreateFolderIfNeeded(string path)
        {
            bool result = true;
            if (!Directory.Exists(path))
            {
                try
                {
                    Directory.CreateDirectory(path);
                }
                catch (Exception)
                {
                    result = false;
                }
            }
            return result;
        }
    }
}
Step 6:
1.Replace the index view code with following to display upload form.
@model MyModel
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<p>
    <input type="text" id="tbx-file-path" value="No file chosen..." readonly="readonly" />
    <span class="btn btn-success fileinput-button">
        <span>Select file...</span>
        @Html.TextBoxFor(m => m.file, new { id = "file-upload", type = "file" })
    </span>
</p>
<p><a class="btn btn-primary" href="#" id="start-upload-button">Start Upload</a></p>
Step 6:
1.Add jquery code in Index View page for ajax fileupload calling.

 var jqXHRData;
        $(document).ready(function () {
            'use strict';
            $('#file-upload').fileupload({
                url: '/File/UploadFile',
                dataType: 'json',
                add: function (e, data) {
                    jqXHRData = data
                },
                done: function (event, data) {
                    if (data.result.isUploaded) {
                        $("#tbx-file-path").val("No file chosen...");
                    }
                    else {

                    }
                    alert(data.result.message);
                },
                fail: function (event, data) {
                    if (data.files[0].error) {
                        alert(data.files[0].error);
                    }
                }
            });
        });
        $("#start-upload-button").on('click', function () {
            if (jqXHRData) {
                jqXHRData.submit();
            }
            return false;
        });
        $("#file-upload").on('change', function () {
            $("#tbx-file-path").val(this.files[0].name);
        });

Run the application you will get below screen.

select a file and click on 'start Upload' button.
file will upload and you can see the uploaded files here..


Downlaod code from here Downlaod.

Conclusion:
I hope this article helpful and understandable for every reader.If you have any suggestion please send me..

Monday, 18 April 2016

How to add Jquery datepicker to TextBox

05:07:00 Posted by raviteja swayampu , No comments
Hello every one welcome again to all of you.In this tutorial i am gonna tell you how to add Jquery Client side date picker in ASP.NET MVC application.
I hope you people know about the Datepicker control in ASP.NET Webforms application.It is a Server side control which allows user to enter date in respective textbox. But, You know that there is now server side controls in ASP.NET MVC.But, It is very easy to integrate datepicker to MVC application.I will explain how to do it and this jquery plugin is also a client side control(There is no problem of post backs like in traditional ASP.NET webforms applications).

Step 1: Create a ASP.NET MVC sample application
1.Click New project-->name it


Step 2: Add Controller  and View
1.Add Home controller and Index view.
HomeController.cs

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
 }

2.Add Index view
3.add following jquery code for displaying datepicker

 $(document).ready(function () {
        $("#txtDate").datepicker();
    });
Index.cshtml:
@{
    ViewBag.Title = "Jquery date picker";
    Layout = null; //make layout null
}
<h2>Jquery date picker</h2>
@*Jquery libraries for date picker --both css and javascript*@
@*Jquery theme styles*@
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<link href="~/Content/bootstrap.css" rel="stylesheet" />
@*Jquery plugin*@
<script src="~/Scripts/jquery-1.10.2.js"></script>
@*Jquery UI Theme styles for dispaying Datepicker*@
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
@*User script for calling datepicker*@
<script type="text/javascript">
    $(document).ready(function () {
        $("#txtDate").datepicker();
    });
</script>
@using (Html.BeginForm())
{
    @Html.Label("Enter date:")<br/>
    @Html.TextBox("txtDate", "", new { style="width:300px;height:30px;"})
    <input type="button" class="btn btn-success" value="Submit" />
}

4.Run the application and click in textbox .

Download source from here Download.
Conclusion:
I hope this tutorial can understanble by every reader.I will meet you in another real time tutorial.


Wednesday, 13 April 2016

How to pass View values to Controller using Jquery

22:04:00 Posted by raviteja swayampu , No comments
We know how to pass data to the controller using Model binding.In this article i am going to explain how to pass the form data from View page to Controller and store the data in Sql server table.
I will explin this in step by step manner.
If you are new to ASP.NET MVC please refer previous tutorials for basics of MVC.

Step 1: Create a MVC web application
1.open visual studio and create a ASP.NET MVC web application and name it Jquery.
Step 2: Create Model class
1.right click Models folder -->Add-->Class-->name it User.cs
2. Create following properties in User.cs Model class.

 public class User
    {
        public string Name { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
    }

Step 3: Add Controller
1.Right click controller folder
2.Add-->New-->Controller-->Name it HomeController.cs
HomeController.cs

using System.Data;
using System.Data.SqlClient;
using Jquery.Models;
using System.Configuration;
namespace Jquery.Controllers
{
    public class HomeController : Controller
    {
        private SqlConnection con;

        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult AddUser(User obj)
        {
            AddDetails(obj);
            return View();
        }
        //To Handle connection related activities
        private void connection()
        {
            string constr = ConfigurationManager.ConnectionStrings["SqlConn"].ToString();
            con = new SqlConnection(constr);
        }
        //To add Records into database 
        private void AddDetails(User obj)
        {
            connection();
            string query = "insert into UserData values(@Name,@City,@Address)";
            SqlCommand com = new SqlCommand(query, con);
            com.CommandType = CommandType.Text;
            com.Parameters.AddWithValue("@Name", obj.Name);
            com.Parameters.AddWithValue("@City", obj.City);
            com.Parameters.AddWithValue("@Address", obj.Address);
            con.Open();
            com.ExecuteNonQuery();
            con.Close();
        }
 }
}

Step 4: Add View page
1.right click on Index action method and add View
2.name it Index.cshtml.
3.In index view add following jquery code

@*Add jquery CDN to the View page*@
    $(document).ready(function () {
        $("#btnSave").click(function () {
            $.ajax(
            {
                type: "POST", //HTTP POST Method
                url: "Home/AddUser", //data sent to the AddUser action method
                data: { //Passing data
                    Name: $("#txtName").val(), //Reading text box values using Jquery
                    City: $("#txtAddress").val(),
                    Address: $("#txtcity").val()
                }
            });
        });
    });
Note: Add jquery CDN to View
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

Now add Form to enter values.
@{
    ViewBag.Title = "Add User";
}
@*Add jquery CDN to the View page*@
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $("#btnSave").click(function () {
            $.ajax(
            {
                type: "POST", //HTTP POST Method
                url: "Home/AddUser", //data sent to the AddUser action method
                data: { //Passing data
                    Name: $("#txtName").val(), //Reading text box values using Jquery
                    City: $("#txtAddress").val(),
                    Address: $("#txtcity").val()
                }
            });
        });
    });
</script>
<h2>www.Mitechdev.com user data</h2>
<fieldset>
    <div class="form-horizontal">
        <div class="editor-label">
            Name
        </div>
        <div class="editor-label">
            <input type="text" id="txtName" />
        </div>
        <div class="editor-label">
            Address
        </div>
        <div class="editor-label">
            <input type="text" id="txtAddress" />
        </div>
        <div class="editor-label">
            City
        </div>
        <div class="editor-label">
            <input type="text" id="txtcity" />
        </div>
        <div class="editor-label">
            <br />
            <input class="btn-default" type="button" id="btnSave" value="Save" />
        </div>
    </div>
</fieldset>
Step 5: Create a table

Now run the application and see in browser..

Enter some data into Fields and click submit and check the data was inserted into the Database or not.
Check below image data you entered in the fields successfuly inserted into Table.

Download the sample code for this application here Download.

Conclusion:
I hope this article is understanble for any people and you learn from this article.


Thursday, 7 April 2016

Jquery Validation plugin in MVC 4

21:42:00 Posted by raviteja swayampu , No comments
What is jquery validation plugin. I think you got this question. It is one of the plugin used along with Jquery. It is a open source plugin we can shape this according to our requirement.
This plugin simplifies client side validation and also offers plenty of customization options. It makes a good choice is you are building some thing from scratch.but also when you’re trying to integrate something into an existing application with lots of existing markup. The plugin comes bundled with a useful set of validation methods, including URL and email validation, while providing an API to write your own methods. All bundled methods come with default error messages in english and translations into 37 other languages.

Note:
official site of this jquery validation plugin is jqueryvalidation.org.you can get code from here and official documentation for this also avilable on this site.

In this article i will explain a simple example of using jquery validation plugin using ASP.NET MVC.
and how  it used in ASP.NET MVC.

Step 1: Create a ASP.NET MVC application using Empty template.
1.open visual studio 2015.
2.select Visual C# -->web-->ASP.NET Web application-->New project window-->select Empty -->Check MVC on bottom-->Add.
3.Project created.

Step 2: Create a Controller
1.Right click Controllers folder-->Add-->Controller-->Select MVC5 Empty Controlller-->name it as "HomeController".
2.generated controller code is like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace jqueryvalidationplugin.Controllers
{
    //Generated controller code is.......
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
}

Step 3: Add libreary files/resource files to view.
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/mytechdev_script.js"></script>

Note: After adding this libreary files to index view goto _Layout.cshtml page and check is there any bootstrap,jquery reference files are added.If they was added comment those resource files.like this.
And you can download the code from official site mentioned in the above link.
Step 4: Add view to Index action Method 1.Right click on Index action method-->Add View-->Select Empty template-->Click Add. replace code with following code for displaying Form: Index.cshtml:
<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title">Simple Form</h3>
    </div>
    <div class="panel-body">
        <form id="signupForm" method="post" class="form-horizontal" action="">
            <div class="form-group">
                <label class="col-sm-4 control-label" for="firstname">First name</label>
                <div class="col-sm-5">
                    <input type="text" class="form-control" id="firstname" name="firstname" placeholder="First name" />
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-4 control-label" for="lastname">Last name</label>
                <div class="col-sm-5">
                    <input type="text" class="form-control" id="lastname" name="lastname" placeholder="Last name" />
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-4 control-label" for="username">Username</label>
                <div class="col-sm-5">
                    <input type="text" class="form-control" id="username" name="username" placeholder="Username" />
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-4 control-label" for="email">Email</label>
                <div class="col-sm-5">
                    <input type="text" class="form-control" id="email" name="email" placeholder="Email" />
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-4 control-label" for="password">Password</label>
                <div class="col-sm-5">
                    <input type="password" class="form-control" id="password" name="password" placeholder="Password" />
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-4 control-label" for="confirm_password">Confirm password</label>
                <div class="col-sm-5">
                    <input type="password" class="form-control" id="confirm_password" name="confirm_password" placeholder="Confirm password" />
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-5 col-sm-offset-4">
                    <div class="checkbox">
                        <label>
                            <input type="checkbox" id="agree" name="agree" value="agree" />Please agree to our policy
                        </label>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-9 col-sm-offset-4">
                    <button type="submit" class="btn btn-primary" name="signup" value="Sign up">Sign up</button>
                </div>
            </div>
        </form>
    </div>
</div>

Step 5: Add script file for validation 1.Add a mytechdev_script.js file to the project in Scripts folder. Note: I added the explanation for code in the script itself.
//this 'setDefaults' checks entire form and executed after 
//there is no errors
$.validator.setDefaults({
    submitHandler: function () {
        //you will get alert there is no errors in form.
        alert( "form submitted!" );
    }
} );
//These plugin is in json format
//All data we sent is in json format.. like below
//jquery event handler loads after all page loads
$(document).ready(function () {
    //plugin validate function
    $("#signupForm").validate({
        //rules for the validation if form values doen't 
        //satify these rules error is displayed
        rules: {
            firstname: "required",  //fields
            lastname: "required",
            username: {
                required: true,
                minlength: 2
            },
            password: {
                required: true,
                minlength: 5
            },
            confirm_password: {
                required: true,
                minlength: 5,
                equalTo: "#password"
            },
            email: {
                required: true,
                email: true
            },
            agree: "required"
        },
        //if field value doesn't satify above rules following error may arise
        messages: {
            firstname: "Please enter your firstname",
            lastname: "Please enter your lastname",
            username: {
                required: "Please enter a username",
                minlength: "Your username must consist of at least 2 characters"
            },
            password: {
                required: "Please provide a password",
                minlength: "Your password must be at least 5 characters long"
            },
            confirm_password: {
                required: "Please provide a password",
                minlength: "Your password must be at least 5 characters long",
                equalTo: "Please enter the same password as above"
            },
            email: "Please enter a valid email address",
            agree: "Please accept our policy"
        },
        errorElement: "em",
        //error placement function 
        //we add styles to the error classes here.
        errorPlacement: function (error, element) {
            // Add the `help-block` class to the error element
            error.addClass("help-block");

            if (element.prop("type") === "checkbox") {
                error.insertAfter(element.parent("label"));
            } else {
                error.insertAfter(element);
            }
        },
        //styles for highlighiting successful value
        highlight: function (element, errorClass, validClass) {
            $(element).parents(".col-sm-5").addClass("has-error").removeClass("has-success");
        },
        //styles for highlighiting error value
        unhighlight: function (element, errorClass, validClass) {
            $(element).parents(".col-sm-5").addClass("has-success").removeClass("has-error");
        }
    });
});
Now run the application press F5.. window is look like this...
When i click on signup form without entering any values into the fields then page look like this..

Check the application by submitting different values into the fields. Download source from here Downlaod  Conclusion: I hope you understand this article and it will very helpful to you also. I will met you again in another article.

Tuesday, 5 April 2016

How to implement Dropdown list in MVC

22:14:00 Posted by raviteja swayampu No comments
How to implement Dropdown list in ASP.NET MVC. In traditional ASP.NET it is very easy to implement just by drag and dropping where we want. But in MVC we need some attention to create Drop Downlist.We have Dropdown list Html helper in ASP.NET MVC but we need to know how to bind data to Dropdown list Html helpers.
we can implement Drop down list in ASP.NET MVC in 2 ways.

1.Using normal HTML Controls(select tag):
We can implement  dropdownlist using HTML <select/> tag like below
 ExampleCode:
<select id="html_dropdown">
    <option>--Select--</option>
    <option>India</option>
    <option>US</option>
    <option>China</option>
    <option>Russia</option>
    <option>United Kingdom</option>
</select>

2.Using HTML helpers:
Method 1:
It is very easy to implement dropdownlist using normal html tags. But, if you want to bind data dynamically to the HTML tags it becomes complicated.To overcome and to make it easy to bind data to Html controls Microsoft introduced HTML helpers Methods.Here we are using Dropdown HTML helper to bind object data to Dropdownlist.
Advantages:
1.It is also easy to implement.
2.Dynamic binding of data is very easy
3.We can easily implement cascading dropdownlists
Note:In method 1 i am sending data from controller using ViewBag.
ExampleCode:

 //Using ViewBag
            List item = new List();
            item.Add(new SelectListItem { Text = "India", Value = "1" });
            item.Add(new SelectListItem { Text = "China", Value = "2" });
            item.Add(new SelectListItem { Text = "United Sates", Value = "3" });
            item.Add(new SelectListItem { Text = "Srilanka", Value = "4" });
            item.Add(new SelectListItem { Text = "Germany", Value = "5" });
            ViewBag.html_helper_dropdown = item;

View code:
@using (Html.BeginForm())
{
    @Html.DropDownList("html_helper_dropdown","--select--")
}


Method 2:
In this i am sending data using ViewData to Controller with the same data source
Code:
List item = new List();
 item.Add(new SelectListItem { Text = "India", Value = "1" });
 item.Add(new SelectListItem { Text = "China", Value = "2" });
 item.Add(new SelectListItem { Text = "United Sates", Value = "3" });
 item.Add(new SelectListItem { Text = "Srilanka", Value = "4" });
 item.Add(new SelectListItem { Text = "Germany", Value = "5" });
ViewData["viewdata_ddl"] = item;

 view code:

<p>Using View data</p>
@using (Html.BeginForm())
{
    @Html.DropDownList("viewbag_dropdown",ViewData["viewdata_ddl"] as List<SelectListItem>, "--select--")
}


Method 3:
Model binding.In this method we are binding the data using Model.This method mainly used for Strongly typed Views.
1.First create a model class with the 2 properties. one for Dropdown values and another for storing the selected value.
Model.cs:
using System.Collections.Generic;
using System.Web.Mvc;
namespace Dropdownlist.Models
{
    public class Model
    {
        public string selectedType { get; set; }
        public IEnumerable CountryList { get; set; }
    }
}

Then prepare data source in controller and send the data through return View() method
Controller code:
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Dropdownlist.Models;
namespace Dropdownlist.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            //Using ViewBag
            List item = new List();
            item.Add(new SelectListItem { Text = "India", Value = "1" });
            item.Add(new SelectListItem { Text = "China", Value = "2" });
            item.Add(new SelectListItem { Text = "United Sates", Value = "3" });
            item.Add(new SelectListItem { Text = "Srilanka", Value = "4" });
            item.Add(new SelectListItem { Text = "Germany", Value = "5" });
            ViewBag.html_helper_dropdown = item;

            //using ViewData
            ViewData["viewdata_ddl"] = item;

            //using Model binding
            var model = new Model
            {
                CountryList = item
             };
            return View(model);
        }
    }
}
View code as follows:

<p>Using Model </p>
@using (Html.BeginForm())
{
    @Html.DropDownListFor(x=>x.selectedType,Model.CountryList,"--select--")
}


Index.cshtml:
@using Dropdownlist.Models
@model Model
@{
    ViewBag.Title = "Dropdown list demo";
}

<h1>Dropdown list</h1>
<h3>Drop downlist using HTML</h3>
<select id="html_dropdown">
    <option>--Select--</option>
    <option>India</option>
    <option>US</option>
    <option>China</option>
    <option>Russia</option>
    <option>United Kingdom</option>
</select>
<br/>
<h3>Using Html helpers </h3>
<p>Method 1:</p><br/>
<p>Here the data was sent from Controller through ViewBag</p>
@using (Html.BeginForm())
{
    @Html.DropDownList("html_helper_dropdown","--select--")
}
<br/>
<p>Method 2:</p>
<p>Using View data</p>
@using (Html.BeginForm())
{
    @Html.DropDownList("viewbag_dropdown",ViewData["viewdata_ddl"] as List<SelectListItem>, "--select--")
}
<p>Method 3:</p>
<p>Using Model </p>
@using (Html.BeginForm())
{
    @Html.DropDownListFor(x=>x.selectedType,Model.CountryList,"--select--")
}
Note: We can also bind the dropdownlist data using ENUM's and arrays also.But, above are the most reliable and used by many developers (in our company also developers uses this methods only.).
Finally i got output like this..


conclusion:
I hope you understand this article.If any one having doubts feel free to ask me through comment i will answer to comments when i am free..