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