Tuesday 27 March 2018

MVC - json - convert /Date(1262322000000)/ to short date string

watch this example on You Tube

 json - convert /Date(1262322000000)/ to short date string
Convert Json DateFormat to simple date format
Convert ISO Date to short date string
Pass and convert date from controller to view (jSon)

1. Stored Procedure
USE [Company]
GO
/****** Object:  StoredProcedure [dbo].[Users_SelectAll]    Script Date: 2018-03-27 1:55:03 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[Users_SelectAll]
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    SELECT * FROM Users
END


2. Controller

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

namespace WebApplication2.Controllers
{
    public class HomeController : Controller
    {
        CompanyEntities db = new CompanyEntities();
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        public JsonResult GetCustomers()
        {
            IEnumerable<Users_SelectAll_Result> model = db.Users_SelectAll().ToList();
            return Json(model);
        }
    }
}

3. View

<div>
    <table id="CustomerTable"></table>
</div>
@section Scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            LoadCustomers();
        });
        function LoadCustomers() {
            var cust = {};
            cust.url = '@Url.Action("GetCustomers", "Home")';
            cust.type = "POST";
            cust.dataType = "json";
            cust.contentType = "application/json";
            cust.success = function (Customers) {
                if (Customers.length > 0) {
                    $('#CustomerTable').append('<tr><th>Customer First Name</th><th>Start Date</th></tr>')
                    $.each(Customers, function (i, Customer) {
                        var dt = new Date(parseInt(Customer.StartDate.replace('/Date(', '')))
                        var dtFinal = AddLeadingZeros(dt.getFullYear(), 4) + '/' +
                            AddLeadingZeros(dt.getMonth() + 1, 2) + '/' +
                            AddLeadingZeros(dt.getDate(), 2)
                        $('#CustomerTable').append('<tr><td>' + Customer.FirstName +
                            '</td><td>' + dtFinal + '</td></tr>')
                    });
                }
            };
            function AddLeadingZeros(number, size) {
                var s = "0000" + number;
                return s.substr(s.length - size);
            }
            $.ajax(cust);
        }
    </script>   
}

MSSQL - Fix Error - Syntaxx error in pattern


Watch solution on YouTube





I am getting this error while searching for something - in my search I have "@" sign - remove it and error is gone.

Wednesday 14 March 2018

MVC - json - Create table dynamically

Watch this example on YouTube


 
1. Stored procedure

USE [Company]
GO
/****** Object:  StoredProcedure [dbo].[Users_SelectAll]    Script Date: 2018-03-14 8:03:29 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[Users_SelectAll]
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    SELECT * FROM Users
END

2.  Controller

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

namespace MVCJsonT.Controllers
{
    public class HomeController : Controller
    {
        CompanyEntities db = new CompanyEntities();
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        public JsonResult GetUsers()
        {
            IEnumerable<Users_SelectAll_Result> model = db.Users_SelectAll().ToList();
            return Json(model);
        }
    }
}

3. View

<div id="UserList"></div>

@section Scripts{
    <script>
        $(document).ready(function () {
            LoadUsers();
        });

        function LoadUsers() {
            var users = {};
            users.url = '@Url.Action("GetUsers", "Home")';
            users.type = "POST";
            users.dataType = "json";
            users.contentType = "application/json";
            users.success = function (Users) {
                if (Users.length > 0) {
                    $('#UserList').append('<tr><th>First Name</th><th>Last Name</th></tr>')
                    $.each(Users, function (i, User) {
                        $('#UserList').append('<tr><td>' + User.FirstName + '</td><td>' + User.LastName + '</td></tr>')
                    });
                }
            };
            $.ajax(users);
        }
    </script>   
}

Saturday 3 March 2018

MVC - jQuery - Tabs - Validate - Show tab with error message on Submit

Watch this tutorial on YouTube


 

1. _Layout
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/Scripts/jquery-1.12.4.min.js")
    @Scripts.Render("~/Scripts/jquery.validate.unobtrusive-ajax.js")
    @Scripts.Render("~/Scripts/jquery-ui-1.12.1.js")
    @Scripts.Render("~/Scripts/jquery.validate.js")
    @Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                </ul>
                @Html.Partial("_LoginPartial")
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryui")
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

2. Model - Customer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace MVCJQueryTabs.Models
{
    public class Customer
    {
        [StringLength(5, MinimumLength =2, ErrorMessage ="{0} must be 2 to 5 chars long")]
        public string FristName { get; set; }

        [StringLength(5, MinimumLength = 2, ErrorMessage = "{0} must be 2 to 5 chars long")]
        public string LastName { get; set; }

        [StringLength(5, MinimumLength = 2, ErrorMessage = "{0} must be 2 to 5 chars long")]
        public string Address { get; set; }

        [StringLength(5, MinimumLength = 2, ErrorMessage = "{0} must be 2 to 5 chars long")]
        public string Country { get; set; }
    }
}

3. Controller - Home
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using MVCJQueryTabs.Models;

namespace MVCJQueryTabs.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            Customer c = new Customer();
            return View(c);
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

4. View - Index

@model MVCJQueryTabs.Models.Customer

<form>
    <div class="container">
        <ul class="tabs">
            <li class="tab-link tab-1 current" data-tab="tab-1">TAB ONE</li>
            <li class="tab-link tab-2" data-tab="tab-2">TAB TWO</li>
            <li class="tab-link tab-3" data-tab="tab-3">TAB THREE</li>
            <li class="tab-link tab-4" data-tab="tab-4">TAB FOUR</li>
        </ul>
        <div id="tab-1" class="tab-content current">
            @Html.LabelFor(x => x.FristName)
            @Html.TextBoxFor(x => x.FristName)
            @Html.ValidationMessageFor(x => x.FristName)
        </div>
        <div id="tab-2" class="tab-content">
            @Html.LabelFor(x => x.LastName)
            @Html.TextBoxFor(x => x.LastName)
            @Html.ValidationMessageFor(x => x.LastName)
        </div>
        <div id="tab-3" class="tab-content">
            @Html.LabelFor(x => x.Address)
            @Html.TextBoxFor(x => x.Address)
            @Html.ValidationMessageFor(x => x.Address)
        </div>
        <div id="tab-4" class="tab-content">
            @Html.LabelFor(x => x.Country)
            @Html.TextBoxFor(x => x.Country)
            @Html.ValidationMessageFor(x => x.Country)
        </div>
    </div>
    <br />
    <input type="submit" value="save" id="btnSave" />
</form>

<script>

    $(document).ready(function () {
        $("#btnSave").click(function () {
            $("form").data("validator").settings.ignore = "";

            var validator = $("form").validate();
            var isValid = $("form").valid();
            if (!isValid) {
                var tab_id = jQuery(validator.errorList[0].element).closest(".tab-content").attr('id');
                $('ul.tabs li').removeClass('current');
                $('.tab-content').removeClass('current');
                $("." + tab_id).addClass('current');
                $("#" + tab_id).addClass('current');
            }
        });

        $('ul.tabs li').click(function () {
            var tab_id = $(this).attr('data-tab');
            $('ul.tabs li').removeClass('current');
            $('.tab-content').removeClass('current');
            $(this).addClass('current');
            $("#" + tab_id).addClass('current');
        });

        $('ul.tabs li').mouseover(function () {
            var tab_id = $(this).attr('data-tab');
            $('ul.tabs li').removeClass('current');
            $('.tab-content').removeClass('current');
            $(this).addClass('current');
            $("#" + tab_id).addClass('current');
        });
    });
</script>

5. CSS

body {
    padding-top: 50px;
    padding-bottom: 20px;
}

/* Set padding to keep content from hitting the edges */
.body-content {
    padding-left: 15px;
    padding-right: 15px;
}

/* Override the default bootstrap behavior where horizontal description lists
   will truncate terms that are too long to fit in the left column
*/
.dl-horizontal dt {
    white-space: normal;
}

/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
    max-width: 280px;
}


ul.tabs{
    width: 15%;
    float: left;
    margin: 0px;
    padding: 0px;
    list-style: none;
}
ul.tabs li{
    width: 100%;
    background: none;
    color: red;
    display: inline-block;
    padding: 10px 0px;
    background-color: green;
}
ul.tabs li.current{
    color: blue;
    background-color: yellow;
}
.tab-content{
    width: 60%;
    height: 100%;
    float: left;
    display:none;
    background: white;
    padding: 15px;
}
.tab-content.current{
    display: inherit;
}

Friday 2 March 2018

MVC - Fix Error - JavaScript runtime error: Unable to set property 'unobtrusive' of undefined or null reference


Watch this example on YouTube



To fix it replace in _Layout

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/Scripts/jquery-1.12.4.min.js")
    @Scripts.Render("~/Scripts/jquery.validate.unobtrusive.js")
    @Scripts.Render("~/Scripts/jquery-ui-1.12.1.min.js")       
</head>

with

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/Scripts/jquery-1.12.4.min.js")
    @Scripts.Render("~/Scripts/jquery.validate.unobtrusive-ajax.js")
    @Scripts.Render("~/Scripts/jquery-ui-1.12.1.min.js")       
</head>

Thursday 1 March 2018

MVC - jQuery - Vertical Tabs manually

Watch this example on YouTube



1. Layout

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/Scripts/jquery-1.12.4.min.js")
    @Scripts.Render("~/Scripts/jquery-ui-1.12.1.min.js")
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                </ul>
                @Html.Partial("_LoginPartial")
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryui")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

2. Index

<div class="container">
    <ul class="tabs">
        <li class="tab-link current" data-tab="tab-1">Tab 1</li>
        <li class="tab-link" data-tab="tab-2">Tab 2</li>
        <li class="tab-link" data-tab="tab-3">Tab 3</li>
        <li class="tab-link" data-tab="tab-4">Tab 4</li>
    </ul>
    <div id="tab-1" class="tab-content current">some text 1</div>
    <div id="tab-2" class="tab-content">some text 2</div>
    <div id="tab-3" class="tab-content">some text 3</div>
    <div id="tab-4" class="tab-content">some text 4</div>
</div>

<script>
    $(document).ready(function () {
        $('ul.tabs li').click(function () {
            var tab_id = $(this).attr('data-tab');
            $('ul.tabs li').removeClass('current');
            $('.tab-content').removeClass('current');
            $(this).addClass('current');
            $("#" + tab_id).addClass('current');
        });
        $('ul.tabs li').mouseover(function () {
            var tab_id = $(this).attr('data-tab');
            $('ul.tabs li').removeClass('current');
            $('.tab-content').removeClass('current');
            $(this).addClass('current');
            $("#" + tab_id).addClass('current');
        });
    });
</script>

3. Add to CSS

ul.tabs{
    width:15%;
    float:left;
    margin: 0px;
    padding:0px;
    list-style:none;
}
ul.tabs li{
    width: 100%;
    background: none;
    color: red;
    display: inline-block;
    padding: 10px 0px;
    background-color: green;
}
ul.tabs li.current{
    color: blue;
    background-color: yellow;
}
.tab-content{
    width: 60%;
    height:30em;
    float:left;
    display: none;
    background:white;
    padding: 15px;
}
.tab-content.current{
    display:inherit;
}