Saturday 27 February 2021

MVC - Custom Validation - Get display name of first, second and third property in both client and server validation

Watch this example on YouTube

 

 

 

1. Validation Function

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

namespace WebApplication10.Models
{
    public class ValidateCheckBoxAttribute: ValidationAttribute, IClientValidatable
    {
        private readonly string[] _fields;
        private const string DefaultErrorMessage = "{0} is mandatory";
        public string firstPropertyName { get; set; }
        public ValidateCheckBoxAttribute(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]);
            PropertyInfo property3 = validationContext.ObjectType.GetProperty(_fields[2]);

            var valueFirst = propertyFirst.GetValue(validationContext.ObjectInstance, null);
            var valueSecond = propertySecond.GetValue(validationContext.ObjectInstance, null);
            var value3 = property3.GetValue(validationContext.ObjectInstance, null);

            var dispFirst = ModelMetadataProviders.Current.GetMetadataForProperty(null, validationContext.ObjectType, _fields[0]);
            var dispSecond = ModelMetadataProviders.Current.GetMetadataForProperty(null, validationContext.ObjectType, _fields[1]);
            var disp3 = ModelMetadataProviders.Current.GetMetadataForProperty(null, validationContext.ObjectType, _fields[2]);
            var firstName = dispFirst.GetDisplayName();
            var secondName = dispSecond.GetDisplayName();
            var th = disp3.GetDisplayName();
            return null;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            Type type = Type.GetType(metadata.ContainerType.FullName);
            var model = Activator.CreateInstance(type);
            var provider = new DataAnnotationsModelMetadataProvider();
            var firstDisplayName = provider.GetMetadataForProperty(() => model, type, _fields[0]);
            var secondDisplayName = provider.GetMetadataForProperty(() => model, type, _fields[1]);
            var thirdDisplayName = provider.GetMetadataForProperty(() => model, type, _fields[2]);
            var one = firstDisplayName.DisplayName;
            var second = secondDisplayName.DisplayName;
            var third = thirdDisplayName.DisplayName;
            var rule = new ModelClientValidationRule
            {
                ValidationType = "validatecheckbox",
                ErrorMessage =  " is mandatory"
            };
            rule.ValidationParameters.Add("fields", string.Join(",", _fields));
            yield return rule;
        }
    }
}


2.  Model

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

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

        [Display(Name="Is Active")]
        public bool IsActive { get; set; }

        [Display(Name = "Last Name etc....")]
        public string LastName { get; set; }
    }
}

MVC - Custom Validation - Error not displayed

 Watch this example on YouTube

To fix it replace

  public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ValidationType = "validatecheckbox"
            };
            rule.ValidationParameters.Add("fields", string.Join(",", _fields));
            yield return rule;
        }

with

 public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ValidationType = "validatecheckbox",
                ErrorMessage =  metadata.GetDisplayName() + " is mandatory"

            };
            rule.ValidationParameters.Add("fields", string.Join(",", _fields));
            yield return rule;
        }

MVC - Custom Validation - Check in checkbox is selected (Checked) in JavaScript

 Watch this example on YouTube


To fix it replace 

 $.validator.addMethod('validatecheckbox', function (value, element, params) {
    var isValid = true;
    if ($(params)[0].fields[0][0].val() == true) {
        if (($(element).val() == '' || $(element).val() == null)) {
            isValid = false;
        }
    }
    return isValid;
});

with

$.validator.addMethod('validatecheckbox', function (value, element, params) {
    var isValid = true;
    if ($(params)[0].fields[0][0].checked == true) {
        if (($(element).val() == '' || $(element).val() == null)) {
            isValid = false;
        }
    }
    return isValid;
});

 

Thursday 25 February 2021

MVC - Custom Validation - Validatate Checkbox and Textbox - Step by Step

 

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

2. Model - Validator

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

namespace WebApplication10.Models
{
    public class ValidateCheckBoxAttribute: ValidationAttribute, IClientValidatable
    {
        private readonly string[] _fields;
        private const string DefaultErrorMessage = "{0} is mandatory";
        public string firstPropertyName { get; set; }
        public ValidateCheckBoxAttribute(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(valueSecond == null & Convert.ToBoolean(valueFirst)== true)
            {
                return new ValidationResult("" + validationContext.DisplayName + " is mandatory");
            }
            return null;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ValidationType = "validatecheckbox",
                ErrorMessage = metadata.GetDisplayName() + " is mandatory(client error)"
            };
            rule.ValidationParameters.Add("fields", string.Join(",", _fields));
            yield return rule;
        }
    }
}

 

3. Javascript validator

$.validator.unobtrusive.adapters.add("validatecheckbox", ["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['validatecheckbox'] = {
        fields: fields
    };
    options.messages['validatecheckbox'] = options.message;
});

$.validator.addMethod('validatecheckbox', function (value, element, params) {

    if ($(element).val() != '') {
        return true;
    }
    var isValid = true;
    if ($(params)[0].fields[0][0].checked == true) {
        if (($(element).val() == '' || $(element).val() == null)) {
            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;

    }

}

 

4. Model - Customer

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

namespace WebApplication10.Models
{
    public class Customer
    {
        [ValidateCheckBox(new string[] { "IsActive", "FirstName"})]
        public string FirstName { get; set; }
        public bool IsActive { get; set; }
    }
}

 

5. Controller

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

namespace WebApplication10.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            Customer model = new Customer();
            return View(model);
        }
        [HttpPost]
        public ActionResult Index(Customer model)
        {
            if (!ModelState.IsValid) { }
            return View(model);
        }

 

6. Index

@model WebApplication10.Models.Customer

@{ Html.EnableClientValidation();}
@using(Html.BeginForm(null, null, FormMethod.Post))
{
    @Html.AntiForgeryToken();
    @Html.CheckBoxFor(x => x.IsActive)
    @Html.TextBoxFor(x => x.FirstName)
    @Html.ValidationMessageFor(x => x.FirstName)
    <input type="submit" value="SUBMIT" />
}

Wednesday 24 February 2021

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

 Watch this example on YouTube


 


To fix it replace in Layout

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

with

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

 

Tuesday 23 February 2021

MVC - Fix Error - Compiler Error Message: CS1003: Syntax error, ',' expected

 Watch this example on YouTube

 

Compiler Error Message: CS1003: Syntax error, ',' expected
Source Error:

public class _Page_Views_Home_Index_cshtml : System.Web.Mvc.WebViewPage<WebApplication6

Source File: C:\Users\livingroomadmin\AppData\Local\Temp\Temporary ASP.NET Files\root\7b262f84\76261bb7\App_Web_index.cshtml.a8d08dba.46cw3-1d.0.cs    Line: 31  



To Fix it replace in your view

@model WebApplication6.Models.Customer;

with 

@model WebApplication6.Models.Customer

 

Monday 22 February 2021

MVC - Fix Error - Object doesn't support property or method 'valid'

 Watch this example on YouTube


 

To fix it replace in Layout

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

with

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

 

Friday 19 February 2021

MVC - Custom Validation - Remote - Additional Fields - Validate on each field change

 

 Watch this example on YouTube


 

Javascript code

@section Scripts{
    
    <script type="text/javascript">
        $(document).ready(function () {
            validateRemote($("form"));
        });
        function validateRemote($form) {
            var remoteElements = $form.find("[data-val-remote]");
            $.each(remoteElements, function (i, element) {
                var $element = $(element);
                var additionalFields = $element.attr("data-val-remote-additionalfields");
                if (additionalFields.length == 0) return;

                var fieldNames = additionalFields.split(",");
                var fNames = $.map(fieldNames, function (fieldName) { return fieldName.replace("*.", ""); });
                $.each(fNames, function (i, fieldName) {
                    $form.find("[id$=" + fieldName + "]").change(function () {
                        if ($element.is(':enabled')) {
                            $element.removeData("previousValue");
                            $element.valid();
                        }
                    });
                });
            });
        }
    </script>    
}

 

MVC - Custom Validation - Remote - Additional Fields - Display dynamic error message

 Watch on YouTube


 Replace 

       public ActionResult ValidateSalary(Customer c)
        {
            string Salary = c.Salary.ToString();
            string res = db.ValidateOnDBSide(Convert.ToInt32(Salary)).FirstOrDefault();
            if(res != string.Empty)
            {
                return Json(false, JsonRequestBehavior.AllowGet);
            }
            return Json(true, JsonRequestBehavior.AllowGet);
        }

with

       public ActionResult ValidateSalary(Customer c)
        {
            string Salary = c.Salary.ToString();
            string res = db.ValidateOnDBSide(Convert.ToInt32(Salary)).FirstOrDefault();
            if(res != string.Empty)
            {
                return Json(res, JsonRequestBehavior.AllowGet);
            }
            return Json(true, JsonRequestBehavior.AllowGet);
        }

Thursday 18 February 2021

MVC - Custom Validation - Remote - Validate passing additional fields (values) to the validation function

 

  Watch this example on YouTube

 

 

1. Stored Procedure

 

CREATE PROCEDURE ValidateOnDBSide
    @value int
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    IF @value > 10
    BEGIN
        Select ''
    END
    ELSE
    BEGIN
        Select 'Error Message Retruned by Stored Procedure'
    END
END
GO 


2. 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.unobtrusive-ajax.min.js")
    @Scripts.Render("~/Scripts/jquery-ui-1.12.1.min.js")
    @Scripts.Render("~/Scripts/jquery.validate.min.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>

3. Model

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

namespace ValidateOnDbSide.Models
{
    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        [Remote(action: "ValidateSalary", controller: "Home", AdditionalFields ="FirstName,LastName",  ErrorMessage ="will never be displayed - it will display message returned by stored procedure")]
        public int Salary { get; set; }
    }
}

4. Controller

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

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

       

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

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

        [AcceptVerbs("Get", "Post")]
        public ActionResult ValidateSalary(Customer c)
        {
            string Salary = c.Salary.ToString();
            string res = db.ValidateOnDBSide(Convert.ToInt32(Salary)).FirstOrDefault();
            if(res != string.Empty)
            {
                return Json(res, JsonRequestBehavior.AllowGet);
            }
            return Json(true, JsonRequestBehavior.AllowGet);
        }


5. View

@model ValidateOnDbSide.Models.Customer

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

@{  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)
    @Html.ValidationMessageFor(x => x.Salary)
    <br />
    <input type="submit" value="Submit" />
}

 

 

Wednesday 17 February 2021

MVC - Custom Validation - Remote - Validate on Database side using Stored Procedure

 Watch this example on YouTube


 

 

1. Stored Procedure

 

CREATE PROCEDURE ValidateOnDBSide
    @value int
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    IF @value > 10
    BEGIN
        Select ''
    END
    ELSE
    BEGIN
        Select 'Error Message Retruned by Stored Procedure'
    END
END
GO 


2. 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.unobtrusive-ajax.min.js")
    @Scripts.Render("~/Scripts/jquery-ui-1.12.1.min.js")
    @Scripts.Render("~/Scripts/jquery.validate.min.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>

3. Model

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

namespace ValidateOnDbSide.Models
{
    public class Customer
    {
        public string FirstName { get; set; }

        [Remote(action: "ValidateSalary", controller: "Home", ErrorMessage ="will never be displayed - it will display message returned by stored procedure")]
        public int Salary { get; set; }
    }
}


4. Controller

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

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

       

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

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

        [AcceptVerbs("Get", "Post")]
        public ActionResult ValidateSalary(string Salary)
        {
            string res = db.ValidateOnDBSide(Convert.ToInt32(Salary)).FirstOrDefault();
            if(res != string.Empty)
            {
                return Json(res, JsonRequestBehavior.AllowGet);
            }
            return Json(true, JsonRequestBehavior.AllowGet);
        }


5. View

@model ValidateOnDbSide.Models.Customer

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

@{  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.Salary)
    @Html.TextBoxFor(x => x.Salary)
    @Html.ValidationMessageFor(x => x.Salary)
    <br />
    <input type="submit" value="Submit" />
}

 

Tuesday 16 February 2021

MVC - Fix Error - Compiler Error Message: CS0103: The name 'maxLength' does not exist in the current context

Watch this example on YouTube

 

 

To Fix it replace

    @Html.TextBoxFor(x => x.or.Column1, new { @class = "editor-field-date"}, maxLength = 10)

with

    @Html.TextBoxFor(x => x.or.Column1, new { @class = "editor-field-date", maxLength = 10})

MVC - Fix Error - The type or namespace name 'WebService' could not be found

 Watch this example on YouTube


 

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

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

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

I am getting this error with this code

   [WebService(Namespace = "http://microsoft.com/webserives/")]
    public class HomeController : Controller
    {


to fix it

add 

using System.Web.Services;

MVC - Fix Error - The type or namespace name 'ArrayList' could not be found

Watch this example on YouTube

 

 

 

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


to fix it replace

  ArrayList x = new ArrayList();

With

     System.Collections.ArrayList x = new System.Collections.ArrayList();

MVC - Fix Error - The type or namespace name 'XmlDocument' could not be found

 Watch this example on YouTube


 this code will give me the error

   XmlDocument doc = new XmlDocument();

 

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


To fix it add

using System.Xml;

MVC - Fix Erro - Cannot implicitly convert type 'void' to 'System.Web.Mvc.ActionResult'

Watch this example on YouTube

 

 

Cannot implicitly convert type 'void' to 'System.Web.Mvc.ActionResult'   
 

To fix it replace

   public ActionvoResult DoSomething()
        {
            return CallSomeFunction();
        }

        public void CallSomeFunction( )
        {
            //do nothing
        }

with 


        public void DoSomething()
        {
             CallSomeFunction();
        }

        public void CallSomeFunction( )
        {
            //do nothing
        }

MVC - Fix Error - The type or namespace name 'RemoteAttribute' could not be found

 Watch this example on YouTube


 

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

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

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


when 


        [Remote(action: "DoSomething", controller: "Home", ErrorMessage ="some error")]
        public string Name { get; set; }

To fix it add

    using System.Web.Mvc;


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

 Watch this example on YouTube


 

To fix it replace

         public ActionResult Index()
        {
            OrderCustomClass model = new OrderCustomClass();
            model.prod = db.SelectProducts();
            int count = model.prod.Count();
            foreach(var item in model.prod)

            {
                var test = item.Name;
            }
            return View(model);
        }

with

        public ActionResult Index()
        {
            OrderCustomClass model = new OrderCustomClass();
            model.prod = db.SelectProducts();
            var vr = (from s in model.prod select s);
            vr = vr.ToList();
            int count = vr.Count();

            foreach(var item in vr)

            {
                var test = item.Name;
            }
            return View(model);
        }

 

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

 Watch this example on YouTube


 

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

 

to fix it replace in Layout file

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryui")

    @Scripts.Render("~/bundles/bootstrap")  
    @Styles.Render("~/Content/themes/base/css", "~/Content/css")
    
    @RenderSection("scripts", required: false)
</body>

with 

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryui")
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/bootstrap")  
    @Styles.Render("~/Content/themes/base/css", "~/Content/css")
    
    @RenderSection("scripts", required: false)
</body>

 

MVC - Ajax - How to validate form and check if it is valid

 Watch this example on YouTube


 

1. Layout  - ensure you have     @Scripts.Render("~/bundles/jqueryval")

 

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

 

2. Index and Java

@model WebApplication1.Models.OrderCustomClass

@{ Html.EnableClientValidation();}
@using (Ajax.BeginForm("", "", null, new { @id = "frm" }))
{
    <div>
        @Html.TextBoxFor(x=>x.or.Column1)
        <input type="submit" onclick="DoSomething()" id="btnSubmit1" value="Submit" />    
    </div>
}
    @section Scripts{
        <script type="text/javascript">
            function DoSomething() {
                $("#frm").validate();
                var IsValid = $("#frm").valid();
                if (IsValid) {
                    alert('valid')
                }
                else {
                    alert('not valid')
                }
            }
        </script>
            }

MVC - Fix Error - 0x800a138f - JavaScript runtime error: Unable to get property 'form' of undefined or null reference

 Watch this example on YouTube


 To fix it replace

@using (Html.BeginForm("", "", new { @id = "frm" }))
{

with

@using (Ajax.BeginForm("", "",null, new { @id = "frm" }))
{

 

Thursday 11 February 2021

MVC - Fix Error - The type or namespace name 'Exchange' does not exist in the namespace 'Microsoft'

 Watch this example on YouTube


 


Error    CS0234    The type or namespace name 'Exchange' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)  


Error when using Microsoft.Exchange.WebServices.Data;

 

To Fix it install NuGet: Microsoft Exchange WebServices

 

MVC - Fix Error - The type or namespace name 'DataVisualization' does not exist in the namespace 'System.Web.UI'

 Watch this example on YouTube


 


Error    CS0234    The type or namespace name 'DataVisualization' does not exist in the namespace 'System.Web.UI' (are you missing an assembly reference?)    

 

Error when using


using System.Web.UI.DataVisualization.Charting;

 

to fix it add reference to 

System.Web.DataVisualization



 

MVC - Chart.js - Create simple Multi Line Chart and load data using Entity Framework

 Watch this example on YouTube


 

1. Table

 

USE [Company]
GO
/****** Object:  Table [dbo].[ChartTest]    Script Date: 2021-02-09 4:17:58 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ChartTest](
    [ProductName] [varchar](50) NULL,
    [Month] [varchar](50) NULL,
    [Amount] [int] NULL,
    [MonthNumber] [int] NULL
) ON [PRIMARY]

GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount], [MonthNumber]) VALUES (N'Apple', N'Jan', 20, 1)
GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount], [MonthNumber]) VALUES (N'Apple', N'Feb', 40, 2)
GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount], [MonthNumber]) VALUES (N'Apple', N'Mar', 22, 3)
GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount], [MonthNumber]) VALUES (N'Apple', N'Apr', 44, 4)
GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount], [MonthNumber]) VALUES (N'Orange', N'Jan', 55, 1)
GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount], [MonthNumber]) VALUES (N'Orange', N'Feb', 22, 2)
GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount], [MonthNumber]) VALUES (N'Orange', N'Mar', 33, 3)
GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount], [MonthNumber]) VALUES (N'Orange', N'Apr', 88, 4)
GO

2. Stored Procedure

-- ================================================
-- Template generated from Template Explorer using:
-- Create Procedure (New Menu).SQL
--
-- Use the Specify Values for Template Parameters
-- command (Ctrl-Shift-M) to fill in the parameter
-- values below.
--
-- This block of comments will not be included in
-- the definition of the procedure.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        <Author,,Name>
-- Create date: <Create Date,,>
-- Description:    <Description,,>
-- =============================================
CREATE PROCEDURE SelectChartTest
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 ChartTest
END
GO
 

3.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.10.2.min.js")
    @Scripts.Render("~/Scripts/Chart.js")
    @Scripts.Render("~/Scripts/Common.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/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

4. Common.js

jQuery.extend({
    getValues: function (url) {
        var result = null;
        $.ajax({
            url: url,
            type: 'get',
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            async: false,
            success: function (data) {
                result = data;
            }
        });
        return result;
    }

});


5. Model

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

namespace BarChartMulti.Models
{
    public class Chart
    {
        public string[] labels { get; set; }
        public List<Datasets> datasets { get; set; }
    }
    public class Datasets
    {
        public string label { get; set; }
        public string[] backgroundColor { get; set; }
        public string[] borderColor { get; set; }
        public string borderWidth { get; set; }
        public int[] data { get; set; }
    }
}


6. Controller

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

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

       public JsonResult MultiLineChartData()
        {
            var data = db.SelectChartTest().ToList();
            var uniqueProducts = from d in data orderby d.ProductName group d by d.ProductName into m select m.Key;
            var uniqueMonths = from a in data orderby a.MonthNumber group a by a.Month into g select g.Key;
            string[] cols = new string[] { "#FF0000", "#800000" };
            int i = 0;
            Chart _chart = new Chart();
            _chart.labels = uniqueMonths.ToArray();
            _chart.datasets = new List<Datasets>();
            List<Datasets> _dataSet = new List<Datasets>();
            foreach(var d in uniqueProducts)
            {
                var colors = new string[uniqueProducts.Count()];
                for (int j = 0; j < colors.Length; j++) colors[j] = cols[i];
                _dataSet.Add(new Datasets()
                {
                    label = d,
                    data = (from a in data where a.ProductName == d select a.Amount.Value).ToArray(),
                    backgroundColor = new string[] {cols[i]},
                    borderColor = new string[] {cols[i]},
                    borderWidth = "1"
                });
                i++;
            }
            _chart.datasets = _dataSet;
            return Json(_chart, JsonRequestBehavior.AllowGet);
        }


7. Index


<canvas id="MultiLineChart" width="400" height="100"></canvas>
<script>
    var c = document.getElementById("MultiLineChart");
    var ctx = c.getContext("2d");
    var tData = $.getValues("/Home/MultiLineChartData");
    var myLineChart = new Chart(ctx, {
        type: 'line',
        data: tData
    });
</script>

 

 

 

Tuesday 9 February 2021

MVC - Chart.js - Create simple Multi Bar Chart and load data using Entity Framework

 Watch this example on YouTube


 

 

 

1. Table

 

USE [Company]
GO
/****** Object:  Table [dbo].[ChartTest]    Script Date: 2021-02-09 4:17:58 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ChartTest](
    [ProductName] [varchar](50) NULL,
    [Month] [varchar](50) NULL,
    [Amount] [int] NULL,
    [MonthNumber] [int] NULL
) ON [PRIMARY]

GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount], [MonthNumber]) VALUES (N'Apple', N'Jan', 20, 1)
GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount], [MonthNumber]) VALUES (N'Apple', N'Feb', 40, 2)
GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount], [MonthNumber]) VALUES (N'Apple', N'Mar', 22, 3)
GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount], [MonthNumber]) VALUES (N'Apple', N'Apr', 44, 4)
GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount], [MonthNumber]) VALUES (N'Orange', N'Jan', 55, 1)
GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount], [MonthNumber]) VALUES (N'Orange', N'Feb', 22, 2)
GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount], [MonthNumber]) VALUES (N'Orange', N'Mar', 33, 3)
GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount], [MonthNumber]) VALUES (N'Orange', N'Apr', 88, 4)
GO

2. Stored Procedure

-- ================================================
-- Template generated from Template Explorer using:
-- Create Procedure (New Menu).SQL
--
-- Use the Specify Values for Template Parameters
-- command (Ctrl-Shift-M) to fill in the parameter
-- values below.
--
-- This block of comments will not be included in
-- the definition of the procedure.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        <Author,,Name>
-- Create date: <Create Date,,>
-- Description:    <Description,,>
-- =============================================
CREATE PROCEDURE SelectChartTest
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 ChartTest
END
GO
 

3.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.10.2.min.js")
    @Scripts.Render("~/Scripts/Chart.js")
    @Scripts.Render("~/Scripts/Common.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/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

4. Common.js

jQuery.extend({
    getValues: function (url) {
        var result = null;
        $.ajax({
            url: url,
            type: 'get',
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            async: false,
            success: function (data) {
                result = data;
            }
        });
        return result;
    }

});


5. Model

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

namespace BarChartMulti.Models
{
    public class Chart
    {
        public string[] labels { get; set; }
        public List<Datasets> datasets { get; set; }
    }
    public class Datasets
    {
        public string label { get; set; }
        public string[] backgroundColor { get; set; }
        public string[] borderColor { get; set; }
        public string borderWidth { get; set; }
        public int[] data { get; set; }
    }
}


6. Controller

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

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

        public JsonResult MultiBarChartDataEF()
        {
            var data = db.SelectChartTest().ToList();
            var uniqueProducts = from d in data orderby d.ProductName group d by d.ProductName into m select m.Key;
            var uniqueMonths = from a in data orderby a.MonthNumber group a by a.Month into g select g.Key;
                      

            string[] cols = new string[] { "#FF0000", "#800000" };
            int i = 0;

            Chart _chart = new Chart();
            _chart.labels = uniqueMonths.ToArray();
            _chart.datasets = new List<Datasets>();
            List<Datasets> _dataSet = new List<Datasets>();

            foreach (var d in uniqueProducts)
            {
                var colors = new string[uniqueMonths.Count()];
                for (int j = 0; j < colors.Length; j++) colors[j] = cols[i];
                _dataSet.Add(new Datasets() {
                    label = d,
                    data = (from a in data where a.ProductName == d select a.Amount.Value).ToArray(),
                    backgroundColor =colors,
                    borderColor = new string[] { "#FF0000", "#800000" },
                    borderWidth = "1"

                });
                i++;
            }
            _chart.datasets = _dataSet;
            return Json(_chart, JsonRequestBehavior.AllowGet);
        }


7. Index


@{
    ViewBag.Title = "Home Page";
}
<canvas id="MultiBarChart" width="400" height="100"></canvas>
<script>
    var c = document.getElementById("MultiBarChart");
    var ctx = c.getContext("2d");
    var tData = $.getValues("/Home/MultiBarChartDataEF");
    var myBarChart = new Chart(ctx, {
        type: 'bar',
        data: tData
    });
</script>

 

Monday 8 February 2021

MVC - Chart.js - Create simple Bar Chart and load data using Entity Framework

 Watch this example on YouTube


 

1. Common.js

jQuery.extend({
    getValues: function (url) {
        var result = null;
        $.ajax({
            url: url,
            type: 'get',
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            async: false,
            success: function (data) {
                result = data;
            }

        });
        return result;
    }
}); 

2. 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.10.2.js")
        @Scripts.Render("~/Scripts/Chart.min.js")
        @Scripts.Render("~/Scripts/Common.js")
</head>

3. Chart.cs


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

namespace WebApplication5.Models
{
    public class Chart
    {
        public string[] labels { get; set; }
        public List<Datasets> datasets { get; set; }
    }
    public class Datasets {
        public string label { get; set; }
        public string[] backgroundColor { get; set; }
        public string[] borderColor { get; set; }
        public string borderWidth { get; set; }
        public int[] data { get; set; }
    }

}

4. Home controller


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

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

        public JsonResult BarChartDataEF()
        {
            var data = db.SelectChartTest().ToList();
            Chart _chart = new Chart();
            _chart.labels = data.Select(x => x.Month).ToArray();
            _chart.datasets = new List<Datasets>();
            List<Datasets> _dataSet = new List<Datasets>();
            _dataSet.Add(new Datasets() {
                label = "Current Year",
                data = data.Select(x => x.Amount.Value).ToArray(),
                backgroundColor = new string[] { "#FFFFFF", "#000000", "#FF00000" },
                borderColor = new string [] { "#FFFFFF", "#000000", "#FF00000" },
                borderWidth = "1"

            });
            _chart.datasets = _dataSet;
            return Json(_chart, JsonRequestBehavior.AllowGet);
        }

6. Index.chtml


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

<canvas id="barChart" width="400" height="100"></canvas>

<script>
    var c = document.getElementById("barChart");
    var ctx = c.getContext("2d");
    var tData = $.getValues("/Home/BarChartDataEF");
    var myBarChart = new Chart(ctx, {
        type: 'bar',
        data: tData
    });
</script>