Thursday 14 December 2017

MSSQL - Fix Error - Incorrect syntax near while inserting records into table

Watch solution on YouTube

to fix it replace
INSERT INTO [dbo].[Customers]
           ([FisrtName]
           ,[LastName])
     VALUES
           ('frank', 'sinatra')
           ('john', 'lennon')
GO

with
INSERT INTO [dbo].[Customers]
           ([FisrtName]
           ,[LastName])
     VALUES
           ('frank', 'sinatra'),
           ('john', 'lennon')
GO

MSSQL - Fix Error - Invalid column name

Msg 207, Level 16, State 1, Line 8
Invalid column name 'frank'.
Msg 207, Level 16, State 1, Line 8
Invalid column name 'sinatra'.



Watch solution on YouTube

To fix it replace
INSERT INTO [dbo].[Customers]
           ([FisrtName]
           ,[LastName])
     VALUES
           ("frank", "sinatra")
GO

with
INSERT INTO [dbo].[Customers]
           ([FisrtName]
           ,[LastName])
     VALUES
           ('frank', 'sinatra')
GO

Wednesday 13 December 2017

MSSQL - Fix Error - An object or column name is missing or empty. For SELECT INTO

Msg 1038, Level 15, State 4, Line 1
An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Change the alias to a valid name.



watch this example on YouTube



To fix it replace
 SELECT FisrtName + N'' '' + LastName
  FROM [Company].[dbo].[Customers]

with
SELECT FisrtName + N' ' + LastName
  FROM [Company].[dbo].[Customers]

Thursday 7 December 2017

MVC - Custom Validation - ensure Display name is shown in error message

Validation - Get Display Name of the filed (property) in error message
also get display name of the filed in both client and server code

Watch this tutorial on YouTube

1. Layout File

<!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.10.2.js")
        @Scripts.Render("~/Scripts/jquery.validate.js")
        @Scripts.Render("~/Scripts/jquery.validate.unobtrusive.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/jqueryval")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

2. Customer class

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

namespace MvcCustomValidation2.Models
{
    public class Customer
    {
        [Display(Name = "First Name")]
        [ValidateCorrespondingRequiredFields(new string[] { "LastName", "FirstName" })]
        public string FirstName { get; set; }

        [Display(Name = "Last Name")]
        [ValidateCorrespondingRequiredFields(new string[] { "FirstName", "LastName" })]
        public string LastName { get; set; }
        public int Age { get; set; }
        public int Salary { get; set; }
    }
}

3. Validation file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using System.Reflection;

namespace MvcCustomValidation2.Models
{
    public class ValidateCorrespondingRequiredFieldsAttribute: ValidationAttribute, IClientValidatable
    {
        private readonly string[] _fields;

        public ValidateCorrespondingRequiredFieldsAttribute(string[] fields)
        {
            _fields = fields;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            PropertyInfo propertyFirst = validationContext.ObjectType.GetProperty(_fields[0]);
            PropertyInfo propertySecond = validationContext.ObjectType.GetProperty(_fields[1]);
            var valueFirst = propertyFirst.GetValue(validationContext.ObjectInstance, null);
            var valueSecond = propertySecond.GetValue(validationContext.ObjectInstance, null);
            if(valueFirst != null && valueSecond == null)
            {
                return new ValidationResult(validationContext.DisplayName + " cannot be empty");
            }
            return null;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ValidationType = "validatecorrespondingrequiredfields",
                ErrorMessage = metadata.GetDisplayName() + " cannot be empty"
            };
            rule.ValidationParameters.Add("fields", string.Join(",", _fields));
            yield return rule;
        }
    }
}
4. Home controller after modifications
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcCustomValidation2.Models;

namespace MvcCustomValidation2.Controllers
{
  
    public class HomeController : Controller
    {
        public ActionResult Test()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Test(Customer c)
        {
            if (ModelState.IsValid)
            {
                // do something here
            }
            return View(c);
        }

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

5. View

@model MvcCustomValidation2.Models.Customer

@{ Html.EnableClientValidation();}
@using (Html.BeginForm(null, null, FormMethod.Post))
{
    @Html.AntiForgeryToken()

    @Html.LabelFor(x => x.FirstName)
    @Html.TextBoxFor(x => x.FirstName)
    <br />

    @Html.LabelFor(x => x.LastName)
    @Html.TextBoxFor(x => x.LastName)
    <br />

    @Html.LabelFor(x => x.Salary)
    @Html.TextBoxFor(x => x.Salary)
    <br />

    @Html.ValidationSummary(String.Empty)
    <input type="submit" value="Click Me" />
}

@section Scripts{
    <script type="text/javascript">
        $.validator.unobtrusive.adapters.add("validatecorrespondingrequiredfields", ["fields"], function (options) {
            var element = options.element;
            var otherNames = options.params.fields.split(',');
            var fields = [];
            $.each(otherNames, function (index, item) {
                fields.push(ElementDetails.getElementDetails(element, item))
            });
            options.rules['validatecorrespondingrequiredfields'] = { fields: fields };
            options.messages['validatecorrespondingrequiredfields'] = options.message;
        });
       
        $.validator.addMethod("validatecorrespondingrequiredfields", function (value, element, params) {
            if ($(element).val() != '') {
                return true;
            }
            var isValid = true;
            $.each(params.fields, function (index, item) {
                if ($(this).val() != '') {
                    isValid = false;
                }
            });
            return isValid;
        });

        ElementDetails = {
            getElementDetails: function (validationElement, item) {
                var retElement = $('#' + item);
                if (retElement.length === 1) {
                    return retElement;
                }
                var name = validationElement.name;
                var index = name.lastIndexOf(".") + 1;
                var id = (name.substr(0, index) + item).replace(/[\.\[\]]/g, "_");
                retElement = $('#' + id);
                if (retElement.length === 1) {
                    return retElement;
                }
                return null;
            }
        }
    </script>   
}


Tuesday 5 December 2017

MVC - Fix Error - Warning: No message defined for - in custom validaiton


watch solution on YouTube

in my case it was typo
to fix it replace
 options.messages['validatecorrespondingrequiredfield'] = options.messsage;
with
 options.messages['validatecorrespondingrequiredfield'] = options.message;

Monday 4 December 2017

MSSQL - Stored procedure inside stored procedure


Watch this example on YouTube



CREATE PROCEDURE GetOrders
AS
BEGIN
    SET NOCOUNT ON;

    Declare @now datetime = getdate()
    Exec SetUpdateRecord @now
    Select * from Orders
END
GO

MVC - Fix Error - An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code Additional information: Input string was not in a correct format.

An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code

Additional information: Input string was not in a correct format.

watch solution on YouTube


to fix it replace

 private string DisplayedErrorMessage = "Either {0] or {1} is required";

with

 private string DisplayedErrorMessage = "Either {0} or {1} is required";

Saturday 2 December 2017

MSSQL - Fix Error - Column, parameter, or variable #7: Cannot find data type BOOL.

error Column, parameter, or variable #7: Cannot find data type BOOL.

watch solution on YouTube

To fix it replace
ALTER TABLE Product

ADD thisIsFinalSale BOOL NOT NULL DEFAULT(0)

GO

with

ALTER TABLE Product

ADD thisIsFinalSale BIT NOT NULL DEFAULT(0)

GO

MSSQL - Fix Error - The name "false" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.

Error

The name "false" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.

Watch solution on YouTube


To fix it replace

ALTER TABLE Product
ADD isFinalSale bit NOT NULL DEFAULT(false)
GO

with

ALTER TABLE Product
ADD isFinalSale bit NOT NULL DEFAULT(0)
GO

Saturday 18 November 2017

MSSQL - Fix Error - Conversion failed when converting the varchar value ' ID is set to: ' to data type int.

Error
Conversion failed when converting the varchar value ' ID is set to: ' to data type int.

Watch solution on YouTube

to fix it replace
Declare @id int = 10
print ' ID is set to: ' + @id
with
Declare @id int = 10
print ' ID is set to: ' + CAST(@id As Varchar)

MSSQL - Microsoft SQL Server Management Studio - How to increase font size

Watch on YouTube

Goto Tools->Options->Environment->Fonts and Colors

MSSQL - Fix Error - Incorrect syntax near '='

Watch this example on YouTube


To fix it replace
Declare @test int = 0
if(@test == 0)
begin
    print 'Zero'
end

with
Declare @test int = 0
if(@test = 0)
begin
    print 'Zero'
end

Saturday 11 November 2017

Saturday 4 November 2017

MVC - fix error - Unable to cast object of type 'System.Int32' to type 'System.String'."

Watch on YouTube


How to set max length of integer

 1. Metadata file


namespace MVCValidationTest.Models
{
    [MetadataType(typeof(SelectTestValidation_Metadata))]
    public partial class SelectTestValidation_Result
    {
        //[StringLength(3, ErrorMessage = "{0} cannot be longer than 3 chars")]
        [Range(1,999)]
        public int test { get; set; }

2. View

  @Html.TextBoxFor(x => x.test, new { maxlength = 3 })

MSSQL - How to fix error - Incorrect syntax near '='.

Watch this example on YouTube


 
To fix it replcae

Declare @temp int = 2;
if @temp == 2
Begin
  print ('found')
End
Else
Begin
  print ('not found')
End

with

Declare @temp int = 2;
if @temp = 2
Begin
  print ('found')
End
Else
Begin
  print ('not found')
End

Thursday 2 November 2017

MVC - How to add MaxLength to TextBoxFor or other controlls using data annotations

watch this example on YouTube


1. Metadata

        [StringLength(3, ErrorMessage ="{0} cannot be longer than 3 chars")]
        public string Name { get; set; }

2. Javascript

$(document).ready(function () {
    $('input[data-val-length-max]').each(
        function (index) {
            $(this).attr('maxlength', $(this).attr('data-val-length-max'));

        });
});

3. Layout

    @Scripts.Render("~/Scripts/MaxLength.js")

MVC - How to display proper name in Validation error message

Watch this example on YouTube



Replace
        [Required(ErrorMessage ="this field is mandatory")]
        public string Name { get; set; }

with
        [Required(ErrorMessage ="{0} field is mandatory")]
        public string Name { get; set; }

or even with
        [Display(Name="Modified Name")]
        [Required(ErrorMessage ="{0} field is mandatory")]
        public string Name { get; set; }

Wednesday 1 November 2017

MVC - Display only 'header' message in @HTml.ValidationSummary

Watch this example on YouTube

to do so replace
    @Html.ValidationSummary("Fix all errors")
with
    @Html.ValidationSummary(true, "Fix all errors")

MVC - Prevent @Html.ValidationSummary from displaying message on loading

Watch this fix on YouTube

 

to fix it add the following to css file
.validation-summary-valid{
    display:none;
}

MVC - How to modify @Html.ValidationSummary so it is not displaying header message

Watch this example on YouTube

To do so replace
   @Html.ValidationSummary("Fix all the errors")
With
   @Html.ValidationSummary("")

Monday 30 October 2017

MVC - How to get all validation error in Controller (after postback)

Watch on YouTube


      
 [HttpPost]
        public ActionResult TestValidations(SelectOrders_Result model)
        {
            foreach(ModelState m in ViewData.ModelState.Values)
            {
                foreach(ModelError er in m.Errors)
                {
                    string errMess = er.ErrorMessage.ToString();
                }
            }

MSSQL - Check against null

Watch this example on YouTube


Declare @NullValue int = 3

IF @NullValue is Null
Begin
    print 'NULL'
End
Else
Begin
    print 'NOT NULL'
End

Saturday 28 October 2017

MVC - How to add css class to @Html.ValidationSummary

Watch this example on YouTube



1. CSS
.float-right{
    float: right;
}

2. VIEW

@using (Html.BeginForm(null, null, FormMethod.Post))
{
    @Html.TextBoxFor(x=>x.Qty)
    <p class="red">@Html.ValidationSummary("Please fix the following errors",
                  new { @class="float-right"})</p>
    <input type="submit" />
}


MVC - How to add css class to @Html.ValidationMessageFor

Watch this example on YouTube


 

1. CSS
.float-right{
    float: right;
}
2.View

    @Html.TextBoxFor(x=>x.Qty)
    <p class="red">@Html.ValidationMessageFor(x => x.Qty, String.Empty, new { @class ="float-right"})</p>

Thursday 26 October 2017

MVC - How to override default error message - The value 'xxx' is not valid for Property

Watch this example on YouTube

1. Add App_GlobalResources folder to solution
2. Add Errors.resx to App_GlobalResources
3. under name in Errors.resx enter PropertyValueInvalid
4. under Value in Errors.resx enter new error message
5. Add Errors.resx to Global.asax
 DefaultModelBinder.ResourceClassKey = "Errors";

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

Watch this example on YouTube


Replace
 @Scripts.Render("~/Scripts/jquery-1.10.2.min.js")
    @Scripts.Render("~/Scripts/jquery.validate.unobtrusive.js")

With

    @Scripts.Render("~/Scripts/jquery-1.10.2.min.js")
    @Scripts.Render("~/Scripts/jquery.validate.min.js")
    @Scripts.Render("~/Scripts/jquery.validate.unobtrusive.js")

Microsoft Excel - format cell so it shows nothing instead of 00:00:00

Watch this example on YouTube



[>=1] d"d" hh:mm:ss; [>0] hh:mm:ss;

MVC - Fix issue when post back in not executed

Watch this example on YouTube


To fix it replace (in view)

  @Html.TextBoxFor(x=>x.Qty)
    @Html.ValidationMessageFor(x => x.Qty)
    <input type="submit" />

With

@using (Html.BeginForm(null, null, FormMethod.Post)) {
    @Html.TextBoxFor(x=>x.Qty)
    @Html.ValidationMessageFor(x => x.Qty)
    <input type="submit" />
}

MSSQL - Change Column Order in Table

Watch this example on YouTube

to change order ensure you have unchecked "Prevent saving changes that require table re-creation" in Tools->Options->Designers

MVC - Fix Error - The type or namespace name 'RequiredAttribute' could not be found (are you missing a using directive or an assembly reference?)

Watch this example on YouTube:



The type or namespace name 'RequiredAttribute' could not be found (are you missing a using directive or an assembly reference?)

to fix it add the following using
using System.ComponentModel.DataAnnotations;

Tuesday 24 October 2017

MVC - DisplayFor - Display nothing (empty) if 0

Watch this example on YouTube




Replace
@Html.DisplayFor(modelItem => item.SomeNumber)

With

 if (item.SomeNumber != 0) {@Html.DisplayFor(modelItem => item.SomeNumber)}

MVC - Fix error - The result of a query cannot be enumerated more than once

 Watch this example on YouTube



to fix it convert function that loads view
replace
        public ActionResult Test()
        {
            OrderClass model = new OrderClass();
            model.or = db.SelectOrders().FirstOrDefault();
            model.pr = db.SelectProducts();
            return View(model);
        }

with
        public ActionResult Test()
        {
            OrderClass model = new OrderClass();
            model.or = db.SelectOrders().FirstOrDefault();
            model.pr = db.SelectProducts().ToList();
            return View(model);
        }

Monday 23 October 2017

MVC - Database First - Stored Procedure - How to add First Empty Record to DropDownList




to add empty record replace
@Html.DropDownListFor(x=>x.or.ProductID, new SelectList(Model.pr, "ProductID", "Name"))

with
@Html.DropDownListFor(x=>x.or.ProductID, new SelectList(Model.pr, "ProductID", "Name"), "")

Saturday 21 October 2017

MVC - fix error - Cannot implicitly convert type 'System.Data.Entity.Core.Objects.ObjectResult' to 'class'

Watch this example on YouTube


Cannot implicitly convert type
'System.Data.Entity.Core.Objects.ObjectResult<MVCDropDownListDBFirst.Models.SelectOrders_Result>'
to 'MVCDropDownListDBFirst.Models.SelectOrders_Result'

to fix it replace
model.or = db.SelectOrders();

with 
model.or = db.SelectOrders().FirstOrDefault();

MVC - Database First - Stored Procedure example - How to populate DropDownList

Watch this example on YouTube


 
1. SQL - Orders Table

USE [Company]
GO

/****** Object:  Table [dbo].[Orders]    Script Date: 2017-10-21 8:39:53 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Orders](
    [OrderID] [int] NULL,
    [Qty] [int] NULL,
    [ProductID] [int] NULL
) ON [PRIMARY]

GO

2. SQL - Product Table

USE [Company]
GO

/****** Object:  Table [dbo].[Product]    Script Date: 2017-10-21 8:40:26 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Product](
    [ProductID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50) NULL,
 CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED
(
    [ProductID] 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

3. Stored Procedures

CREATE PROCEDURE SelectProducts
AS
BEGIN
    SET NOCOUNT ON;
    SELECT * FROM Product
END
GO

CREATE PROCEDURE SelectOrders
AS
BEGIN
    SET NOCOUNT ON;
    SELECT * FROM Orders
END
GO

4. Model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MVCDropDownListDBFirst.Models;

namespace MVCDropDownListDBFirst.Models
{
    public class OrderClass
    {
        public SelectOrders_Result or { get; set; }
        public IEnumerable<SelectProducts_Result> pr { get; set; }
    }
}

5. Controller

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

namespace MVCDropDownListDBFirst.Controllers
{
    public class HomeController : Controller
    {
        CompanyEntities db = new CompanyEntities();

        public ActionResult Test()
        {
            OrderClass model = new OrderClass();
            model.or = db.SelectOrders().FirstOrDefault();
            model.pr = db.SelectProducts();
            return View(model);
        }


6. View

@model MVCDropDownListDBFirst.Models.OrderClass
@{
    ViewBag.Title = "Test";
}

<h2>Test</h2>

@Html.DropDownListFor(x=>x.or.ProductID, new SelectList(Model.pr, "ProductID", "Name"))


MSSQL - How to sum each column values

Watch this example on YouTube




 SELECT        Qty, Price
FROM            Orders
UNION ALL
SELECT        SUM(Qty) AS Expr1, SUM(Price) AS Expr2
FROM            Orders

MSSLQ - Query to load all stored procedures that start with particular name

Watch this example on YouTube




Select * FROM Company.Information_Schema.routines
Where routine_type= 'PROCEDURE'
AND routine_name Like ('User%')

MSSQL - Query to load all tables in database that start with particular name

Watch on YouTube



Select * from Company.Information_Schema.Tables Where Table_Name Like 'User%'

MVC - JavaScript - How to clear Select List

Watch this example on YouTube:


HTML:

<select id="Product">
    <option>Product1</option>
    <option>Product2</option>
    <option>Product3</option>
    <option>Product4</option>
    <option>Product5</option>
</select>
<input type="submit" value="clear select list" id="btnClear" />

JAVASCRIPT:

@section Scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnClear").click(function (e) {
                var SelectOption = document.getElementById("Product");
                for (var i = SelectOption.options.length - 1; i >= 0; i--) {
                    SelectOption.remove(i);
                }
            });
        });
    </script>
}

MVC - JavaScript - Convert Datetime to Date

Watch this example on YouTube


@section Scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            var datetime = '2017-10-18 12:00 AM';
            alert("DateTime: " + datetime);
            var date = datetime.split(' ')[0];
            alert("Date: " + date);

Friday 20 October 2017

MVC - FIx error - Index and length must refer to a location within the string

Index and length must refer to a location within the string.
Parameter name: length


Watch solution on YouTube

To fix it replace
            string test = "abc";
            test = test.Substring(0, 5);
with

string test = "abc";
            int StringLength = test.Trim().Length > 5 ? 5 : test.Trim().Length;
            test = test.Substring(0, StringLength);


 

Wednesday 18 October 2017

MVC - How to pass value from Controller to View using JSon


Watch this example on YouTube

 

Controller

       public JsonResult GetSomeValue()
        {
            return Json(new
            {
                SomeValue = "here is my value"
            });
        }

View - HTML

<input type="submit" value="Display Some Value" id="btnJson" />

View JavaScript


@section Scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnJson").click(function (e) {
                var val = {};
                val.url='@Url.Action("GetSomeValue", "Home")';
                val.type= "POST";
                val.dataType = "json";
                val.contentType = "application/json";
                val.success = function(response){
                    alert(response.SomeValue);
                };
                $.ajax(val);
            });
        });
    </script>
}

Monday 16 October 2017

MVC - jQuery - Trick to quickly lear select element (drop down list)


Watch on YouTube

<div>
    <select id="Products">
        <option>Product 1</option>
        <option>Product 2</option>
        <option>Product 3</option>
        <option>Product 4</option>
        <option>Product 5</option>
    </select>
</div>
<input type="submit" value="clear drop down list" id="btnClear" />

and scripts

@section Scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnClear").click(function (e) {
                $("#Products").empty();
            });
        });
    </script>
}

Saturday 14 October 2017

MVC - jSon, JavaScript, jQuery - How to creat radiobuttons programmatically, load them with data and get selected ID and Name


Watch this example on YouTube:


Controller:

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

namespace MVC_RadioButton.Controllers
{
    public class HomeController : Controller
    {
        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 GetValues()
        {
            List<User> u = new List<User>();
            u.Add(new User(111, "ANNA"));
            u.Add(new User(222, "BOB"));
            u.Add(new User(333, "JOHN"));
            u.Add(new User(444, "IRA"));
            return Json(u.Select(x => new
            {
                ID = x.ID,
                NAME = x.Name
            }));

        }
    }

    public class User
    {
        public int ID { get; set; }
        public string Name { get; set; }

        public User(int id, string name)
        {
            ID = id;
            Name = name;
        }
    }
}

View:

@{
    ViewBag.Title = "Home Page";
}

<div id="test"></div>
<input type="submit" value="Get Selected Values" name="btn" id="btnRadio" />

<div class="jumbotron">
    <h1>ASP.NET</h1>
    <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
    <p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p>
</div>

<div class="row">
    <div class="col-md-4">
        <h2>Getting started</h2>
        <p>
            ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
            enables a clean separation of concerns and gives you full control over markup
            for enjoyable, agile development.
        </p>
        <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301865">Learn more &raquo;</a></p>
    </div>
    <div class="col-md-4">
        <h2>Get more libraries</h2>
        <p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p>
        <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301866">Learn more &raquo;</a></p>
    </div>
    <div class="col-md-4">
        <h2>Web Hosting</h2>
        <p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
        <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301867">Learn more &raquo;</a></p>
    </div>
</div>

@section Scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            var entries = {};
            entries.url = '@Url.Action("GetValues", "Home")';
            entries.type = "POST";
            entries.dataType = "json";
            entries.contentType = "application/json";
            entries.success = function (r) {
                $('#test').empty();
                for (var i = 0; i < r.length; i++) {
                    var label = $("<label for'" + r[i].ID + "'id='RadioButton'>" + r[i].NAME + "</label>");
                    label.appendTo('#test');
                    var radioButton = $("<input type='radio' class='SomeClass' id='"+ r[i].NAME + "' name='SomeName' value='" + r[i].ID + "'/>");
                    radioButton.appendTo('#test');
                }
            };
            entries.error = function (){alert("Error retrieving values")};
            $.ajax(entries);

            $("#btnRadio").click(function(e){
                var ID = $("input[name='SomeName']:checked").val();
                var Name = $("input[name='SomeName']:checked").attr('id');
                alert("Checked ID: " + ID + " checked name: " + Name);
            });
        });
    </script>
    }



Thursday 12 October 2017

MVC - Json - Populate Drop Down List (select) using Json


Watch this example on YouTube



1. SQL



USE [Test]
GO
/****** Object:  Table [dbo].[Product]    Script Date: 2017-10-12 9:40:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Product](
    [ProductID] [int] IDENTITY(1,1) NOT NULL,
    [ProductName] [varchar](50) NOT NULL,
 CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED
(
    [ProductID] 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
SET IDENTITY_INSERT [dbo].[Product] ON

GO
INSERT [dbo].[Product] ([ProductID], [ProductName]) VALUES (1, N'Monitor')
GO
INSERT [dbo].[Product] ([ProductID], [ProductName]) VALUES (2, N'Computer')
GO
INSERT [dbo].[Product] ([ProductID], [ProductName]) VALUES (3, N'Mouse')
GO
INSERT [dbo].[Product] ([ProductID], [ProductName]) VALUES (4, N'Laptop')
GO
INSERT [dbo].[Product] ([ProductID], [ProductName]) VALUES (5, N'TV')
GO
SET IDENTITY_INSERT [dbo].[Product] OFF
GO
/****** Object:  StoredProcedure [dbo].[GetProducts]    Script Date: 2017-10-12 9:40:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        <Author,,Name>
-- Create date: <Create Date,,>
-- Description:    <Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[GetProducts]
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    Select * from Product
END

GO
2. Controller

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

namespace MVCJsonDropDownList.Controllers
{
    public class HomeController : Controller
    {
        TestEntities db = new TestEntities();

        public JsonResult LoadProducts()
        {
            IEnumerable<GetProducts_Result> res = db.GetProducts();
            return Json(res.Select(x => new
            {
                ID = x.ProductID,
                Name = x.ProductName
            }));
        } 



3. View

<select id="Product">
    <option></option>
</select>

<input type="submit" value="Load Products" name="btn" id="btnClick" />

 

4. View - JavaScript
@section Scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnClick").click(function (e) {
                var d = {};
                d.url = '@Url.Action("LoadProducts", "Home")';
                d.type = "POST";
                d.dataType = "json";
                d.contentType = "application/json";
                d.success = function (r) {
                    $("#Product").empty();
                    $("#Product").prepend("option value='' selected='selected'></option>");
                    for (var i = 0; i < r.length; i++) {
                        $("#Product").append('<option value="' + r[i].ID + '">' + r[i].Name + '</option>');               
                    }
                };
                $.ajax(d);
            });
        });
    </script>   
}

Wednesday 11 October 2017

MVC - Json - Fix Error - JavaScript runtime error: Invalid character


watch on youtube

To fix it replace

del.error = function(msg){
   alert(JSON.parse(msg.responseText));
}

with

del.error = function (x, status, er){
   var elem = document.createElement('html');
   elem.innerHTML = x.response.Text;
   alert(elem.getElementsByTagName('title')[0].innerHTML);
}

MVC - Unit Testing - How to add breakpoint



Watch this example on YouTube

Add breakpoint as usual then press Ctrl + R and Ctrl + T

MVC - Unit Testing - Fix errors - The type or namespace name 'ViewResult' could not be found (are you missing a using directive or an assembly reference?)


Errors
The type 'System.Web.Mvc.ActionResult' is defined in an assembly that is not referenced.

The type 'System.Web.Mvc.Controlleris defined in an assembly that is not referenced.

The type or namespace name 'ViewResult' could not be found (are you missing a using directive or an assembly reference?)

Watch the solution on YouTube:


To fix it add the following reference: System.Web.Mvc and the following using: System.Web.Mvc


Monday 9 October 2017

MVC - Json - Fix error The resource cannot be found


Watch this example on Youtube:

to fix it replace

something.url = "/Controller/Method";

with

something.url = '@url.Action("Controller", "Method")';

Monday 18 September 2017

MVC - Json - How to pass Object (class) from View to Controller using Json (JavaScript) - another example


Watch this example on YouTube


 
1. View
<input type="submit" value="click me" id="btnClick" />

@section Scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnClick").click(function (e) {
                var MyUser = {};
                MyUser.ID = 222;
                MyUser.FName = "FRANK";
                MyUser.LName = "SINATRA";
                MyUser.url = "@Url.Action("TestFunction", "Home")";
                MyUser.type = "POST";
                MyUser.dataType = "json";
                MyUser.data = JSON.stringify({ usr: MyUser });
                MyUser.contentType = "application/json";
                MyUser.success = function (response) {
                    alert("success")
                };
                MyUser.error = function (response) {
                    alert("error")
                };
                $.ajax(MyUser);

            });
        });
    </script>   
}

2. Controller

      [HttpPost]
        public ActionResult TestFunction(User usr)
        {
            return Json(new
            {
                ResultValue = "Some Value"
            });
        }

    }

   public class User
    {
        public int ID { get; set; }
        public string FName { get; set; }
        public string LName { get; set; }
    }
}


Saturday 16 September 2017

MVC - Json - How to pass Object (class) from View to Controller using Json (JavaScript)



watch this example on YouTube


1. View

<input type="submit" value="Click Me" name="btn" id="btnClick" />

@section Scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnClick").click(function (e) {
                var MyUser = {};
                MyUser.ID = 123;
                MyUser.FName = "FRANK";
                MyUser.LName = "ZAPPA";

                $.ajax({
                    url: '@Url.Action("TestFunction", "Home")',
                    type: "POST",
                    data: '{usr: ' + JSON.stringify(MyUser) + '}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        alert("Success");
                    },
                    error: function (xhr, status, error) {
                        alert("Failed");
                    }
                });
            });
        });
    </script>   
}

2. Controller

        [HttpPost]
        public ActionResult TestFunction(User usr)
        {
            return Json(new
            {
                ResultValue = "something here"
            });
        }

    }

    public class User
    {
        public int ID { get; set; }
        public string FName { get; set; }
        public string LName { get; set; }
    }
}

Monday 7 August 2017

MVC - Json - redirect to acction on success


Watch this tutorial on YouTube:

View

<input type="submit" value="click me" id="btnClick" />

@section scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnClick").click(function () {
                var f = {};
                f.url = '@Url.Action("TestFunction", "Home")';
                f.type = "POST";
                f.dataType = "json";
                f.contentType = "application/json";
                f.success = function (response) {
                    alert("SUCCESS");
                    window.location.href = response.Url;
                };
                f.error = function () {
                    alert("FAILED");
                };
                $.ajax(f);
            });
        });
    </script>

Controller

           [HttpPost]
           public ActionResult TestFunction()
        {
            var redirectUrl = new UrlHelper(Request.RequestContext).Action("About", "Home");
            return Json(new { Url = redirectUrl });
        }

MVC - How to pass multiple values from JavaScript (Json) to Controller

Watch this example on YouTube



View

<input type="submit" value="click me" id="btnClick" />

@section scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnClick").click(function () {
                var f = {};
                f.url = '@Url.Action("TestFunction", "Home")';
                f.type = "POST";
                f.dataType = "json";
                f.data = JSON.stringify({ ID: 123, FName: "FRANK", LName: "SINATRA" });
                f.contentType = "application/json";
                f.success = function (response) {
                    alert("success");
                };
                f.error = function (response) {
                    alert("failed");
                };
                $.ajax(f);
            });
        });

    </script>   
}

Controller

        public JsonResult TestFunction(int ID, string FName, string LName)
        {
            return Json(new
            {
                resut = "OK"
            });
        }

Wednesday 26 July 2017

Catch all unhandled exceptions on Controll level

watch this example on YouTube

add this method at the end of your controller

        protected override void OnException(ExceptionContext filterContext)
        {
            base.OnException(filterContext);
            Exception e = filterContext.Exception;
            //loging(e.Message.ToString());
            filterContext.ExceptionHandled = true;
            filterContext.Result = new ViewResult()
            {
                ViewName = "Error"
            };
        }

to create dummy exception
       throw new System.ArgumentException("something is wrong");

Tuesday 25 July 2017

MVC - Fix Error - CS1660: Cannot convert lambda expression to type 'string' because it is not a delegate type


watch solution on YouTUbe



CS1660: Cannot convert lambda expression to type 'string' because it is not a delegate type

to fix it replace 

  @Html.Label(model => model.LastName)
with
 @Html.Label(Model.First().LastName)

Monday 17 July 2017

MVC - jQuery - dynamically change width of textbox or EditorFor

Watch this example on YouTube
<iframe width="560" height="315" src="https://www.youtube.com/embed/FjX4YbTWMzE?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>

add ID to EditorFor
    @Html.EditorFor(model => model.CompanyName, new { htmlAttributes = new { @class = "form-control", @id="myText" } })

add this script
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")

    <script type="text/javascript">
        $(document).ready(function () {
            var textVal = $('#myText').val();
            $('#myText').css('width', ((textVal.length + 2) * 10).toString() + 'px');
        });     
    </script>
}

MVC - Create DropDownList with prepopulated data - for instance with Yes/No


Watch this example on YouTube


@Html.DropDownList("SomeName", new[]
{
    new SelectListItem{Text="YES", Value="1" },
    new SelectListItem {Text="NO", Value="2" }
}, "", new { @id="IsActive"})

MVC - jQuery - Get value of selected radio button

Watch this example on YouTube


Html:

USD: @Html.RadioButton("Currency", "USD")
CAD: @Html.RadioButton("Currency", "CAD")
<input type="button" onclick="CheckSelected()" value="click me" />

jQuery

@section Scripts {
    <script type="text/javascript">
        function CheckSelected() {
            var selected = $("input[name='Currency']:checked").val();
            alert(selected);
        }

        $(document).ready(function () {
      
        });
    </script>
}

MSSQL - Fix Error - Conversion failed when converting the varchar value 'Select * from Cities where ID = ' to data type int.

 Watch this on YouTube



Msg 245, Level 16, State 1, Line 5
Conversion failed when converting the varchar value 'Select * from Cities where ID = ' to data type int.


to fix it replace

Declare @ID int = 1

Declare @SQL varchar(max)

Set @SQL = 'Select * from Cities where ID = ' +  @ID

exec (@SQL)

with

Declare @ID int = 1

Declare @SQL varchar(max)

Set @SQL = 'Select * from Cities where ID = ' + CAST( @ID AS VARCHAR)

exec (@SQL)

Wednesday 19 April 2017

MSSQL - Fix Error - Conversion failed when converting date and/or time from character string.



Msg 241, Level 16, State 1, Line 5
Conversion failed when converting date and/or time from character string.

Watch solution on YouTube



To fix it replace
Declare @SQL varchar(max)
Declare @DateFrom Datetime = '1/1/2000'

Set @SQL = 'Select * FROM Users Where StartDate > ' +  @DateFrom

Exec  ( @SQL )

With


Declare @SQL varchar(max)
Declare @DateFrom Datetime = '1/1/2000'

Set @SQL = 'Select * FROM Users Where StartDate > ' + Convert(Varchar, @DateFrom, 101)

Exec  ( @SQL )

Tuesday 18 April 2017

MSSQL - Pass multiple values to single paramenter in stored procedure - pass varchar



Watch on YouTube


1. Stored Procedure

CREATE PROCEDURE PassMultipleNames
    @NameList varchar(max)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT * FROM Product Where ',' + Convert(varchar(max), @NameList) + ','
     Like '%,' + Convert(varchar(max), Name) + ',%'
END

2. Calling Stored Procedure

Exec PassMultipleNames 'Sofa,Chair,Window'

MVC - Fix Error - 0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'dialog'


 Watch On YOUTUBE


0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'dialog'

to fix it replace


    <script type="text/javascript">
        $(function() {
            $("#Display-Message").dialog({
                modal: true,
                buttons: {OK: function(){$(this).dialog("close");}}
            });
        });
    </script>


with

    @section scripts{
    <script type="text/javascript">
        $(function() {
            $("#Display-Message").dialog({
                modal: true,
                buttons: {OK: function(){$(this).dialog("close");}}
            });
        });
    </script>
       }

MSSQL - Pass multiple values to single paramenter in stored procedure - pass integers


Watch on YOUTUBE


1. Stored Procedure

CREATE PROCEDURE TestProductIDs
    @IDList varchar(max)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    Declare @SQL varchar(max) = 'Select * from Product where ProductID in (' + @IDList + ')';
    Exec (@SQL);
END
GO

2. Calling Stored Procedure

exec TestProductIDs '2, 5, 7'

MVC - @HTML.Label - Add white space


Watch on YouTube



CSS
.White-Space{
    margin-left: .5em;
}

HTML
@Html.Label(" ", new { @class = "White-Space" })

Thursday 30 March 2017

MS SQL - Fix Error - Incorrect syntax near the keyword 'VIEW'.


Watch this example on YOuTube


Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'VIEW'.

To fix it replace
IF EXISTS (Select * FROM sys.views where name='TestView')
ALTER VIEW [dbo].[TestView]
AS
SELECT        dbo.Companies.*
FROM            dbo.Companies
GO

with

IF EXISTS (Select * FROM sys.views where name='TestView')
Drop View [dbo].TestView
Go
CREATE
VIEW [dbo].[TestView]
AS
SELECT        dbo.Companies.*
FROM            dbo.Companies
GO

C# - Fix Error - Cannot implicitly convert type 'bool?' to 'bool'.


Watch this example on YouTube

Error    CS0266    Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)

To fix it replace

    string test = "FALSE";
            bool? test2 = null;
            if (test2)
            {
                test = "OK";
            }

with
    string test = "FALSE";
            bool? test2 = null;
            if (test2 != null)
            {
                test = "OK";
            }

Thursday 23 March 2017

MVC - Database First - Display 2 models in 1 view



Watch this example on YouTube

1. Tables
CREATE TABLE [dbo].[Product](
    [ProductID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50) NULL,
 CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED
(
    [ProductID] 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


CREATE TABLE [dbo].[ProductHistory](
    [HistoryID] [int] IDENTITY(1,1) NOT NULL,
    [ProductID] [int] NULL,
    [PreviousName] [varchar](50) NULL,
    [NewName] [varchar](50) NULL,
 CONSTRAINT [PK_ProductHistory] PRIMARY KEY CLUSTERED
(
    [HistoryID] 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

2.SP
CREATE PROCEDURE [dbo].[LoadParticularProduct]
    @Id int
AS
BEGIN
    SET NOCOUNT ON;

    Select * From Product Where ProductID = @Id
END

GO


CREATE PROCEDURE [dbo].[LoadProductHistory]
    @ProductID int
AS
BEGIN
    SET NOCOUNT ON;

    Select * From ProductHistory Where ProductID = @ProductID Order By ProductID
END

GO



CREATE PROCEDURE [dbo].[LoadProducts]
AS
BEGIN
    SET NOCOUNT ON;

    Select * From Product
END

GO



CREATE PROCEDURE [dbo].[UpdateProduct]
    @ProductID int,
    @ProductName varchar(50)
AS
BEGIN
    SET NOCOUNT ON;

    Declare @PreviousProductName varchar(50) = (Select Name From Product Where ProductID = @ProductID)
    Update Product Set Name = @ProductName Where ProductID = @ProductID
    Insert Into ProductHistory (ProductID, PreviousName, NewName) Values
        (@ProductID, @PreviousProductName, @ProductName)
END

GO

3.New class in model
    public class ProductList
    {
        public LoadParticularProduct_Result prod { get; set; }
       public IEnumerable<LoadProductHistory_Result> hist { get; set; }
    }
4. Controller

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

namespace MVC2Model.Controllers
{
    public class ProductController : Controller
    {
        CompanyEntities db = new CompanyEntities();
        // GET: Product
        public ActionResult Index()
        {
            var res = from s in db.LoadProducts()
                      select s;
            return View(res);
        }

        public ActionResult Edit(int id)
        {
            ProductList pr = new ProductList();
            pr.prod = db.LoadParticularProduct(id).FirstOrDefault();
            if(pr.prod == null)
            {
                return HttpNotFound();
            }
            pr.hist = db.LoadProductHistory(id);
            return View(pr);
        }

        [HttpPost]
        public ActionResult Edit(int id, FormCollection col)
        {
            if (ModelState.IsValid)
            {
                db.UpdateProduct(id, col["prod.Name"]);
            }
            return RedirectToAction("Index");
        }
    }
}

5. View Index
@model IEnumerable<MVC2Model.Models.LoadProducts_Result>
@{
    ViewBag.Title = "Index";
}

<table>
    <tr>
        <th>
            @Html.LabelFor(model=>model.First().Name)
        </th>
        <th></th>
    </tr>
    @foreach(var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem=>item.Name)
            </td>
            <td>
                @Html.ActionLink("Edit/View Product", "Edit", new { id=item.ProductID})
            </td>
        </tr>
    }
</table>

6. View - Edit

@model MVC2Model.Models.ProductList
@{
    ViewBag.Title = "Edit";
}

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <table>
        <tr>
            <th>
                @Html.LabelFor(model=>model.prod.Name)
            </th>
            <th></th>
        </tr>
        <tr>
            <td>
                @Html.EditorFor(model=>model.prod.Name)
            </td>
            <td>
                <input type="submit" value="save" />
            </td>
        </tr>
    </table>
}
<table>
    <tr>
        <th>
            @Html.LabelFor(model=>model.hist.First().PreviousName)
        </th>
        <th>
            @Html.LabelFor(model => model.hist.First().NewName)
        </th>
    </tr>
    @foreach(var item in Model.hist)
    {
        <tr>
            <td>
                @Html.DisplayFor(model=>item.PreviousName)
            </td>
            <td>
                @Html.DisplayFor(model => item.NewName)
            </td>
        </tr>
    }
</table>