Watch this example on YouTube
ALter Table Test01
Alter Column RealName Varchar(100)
Watch this example on YouTube
ALter Table Test01
Alter Column RealName Varchar(100)
Watch this example on YouTube
exec sp_rename 'TableName.CurrentColumnName', 'NewColumnName', 'COLUMN'
Watch this example on YouTube
exec sp_rename 'CurrentTableName' , 'NewTableName'
Watch this example on YouTube
To fix it replace
Alter Table Test1
Add IsValid bit not null Default 0
with
IF COL_LENGTH('dbo.Test1', 'IsValid') Is Null
Begin
Alter Table Test1
Add IsValid bit not null Default 0
End
Watch this example on YouTube
IF COL_LENGTH('dbo.Test3', 'IsValid') is null
Begin
Alter Table Test3 Add IsValid bit not null default 0
End
Select * from Test3
Watch this example on YouTube
To fix it replace
Alter Table Test1
Add IsValid bit not null
with
Alter Table Test1
Add IsValid bit not null Default 0
Watch this example on YouTube
1. View
@{
ViewBag.Title = "Home Page";
}
<div class="AddPopUp">
@Html.Label("Add pop up")
</div>
<div class="modal fade" id="MyPopUp" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
here are going your controls etc
</div>
</div>
</div>
</div>
@section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$(".AddPopUp").click(function (e) {
$('#MyPopUp').modal('show');
});
});
</script>
}
2. CSS
.modal-content{
height: 500px;
width: 700px;
}
Watch this example on YouTube
1. Model
public interface IExtensionTest
{
void DoSomething();
}
public class ExtensionTest: IExtensionTest
{
public void DoSomething() { }
}
public static class SomethingElse {
public static string ReturnSomething(this IExtensionTest t, string s)
{
return "returning: " + s;
}
}
2. Controller
public ActionResult Index()Watch this example on YouTube
Watch this example on YouTube
TimeSpan startSomething = new TimeSpan(8, 0, 0);
TimeSpan endSomething = new TimeSpan(16, 0, 0);
TimeSpan now = DateTime.Now.TimeOfDay;
if ((now > startSomething) && (now < endSomething))
{
//do something here
}
Watch this example on YouTube
if (System.DateTime.Now.DayOfWeek == DayOfWeek.Friday)
{
// do somehting here
}
Watch this example on YouTube
String t = Convert.ToDateTime(DateTime.Now).ToUniversalTime().ToString("yyyy/MM/dd HH:mm UTC");
Watch this example on YouTube
1. PowerShell File
$wshell = New-Object -ComObject Wscript.Shell
$wshell.Popup("Hello World", 0, "Done", 0x1)
2. Bat file
Powershell.exe -executionpolicy remotesigned -File "C:\Temp\PopupTest.ps1"
Watch this example on YouTube
1. Task
using System.Web.Mvc;
using System.Threading.Tasks;
namespace ValidateOnDbSide.Controllers
{
public class BusinessController : Controller
{
public async Task<string> DoSomething()
{
return await Task.Run(() => test());
}
public string test()
{
return "test";
}
}
}
2. Controller
using System.Threading.Tasks;
namespace ValidateOnDbSide.Controllers
{
public class HomeController : Controller
{
CompanyEntities db = new CompanyEntities();
public async Task<ActionResult> Index()
{
BusinessController b = new BusinessController();
//Task c = b.DoSomething();
string res = await b.DoSomething();
return View();
}
Watch this example on YouTube
Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.
To fix it replace
public ActionResult Index()
{
BusinessController b = new BusinessController();
b.DoSomething();
return View();
}
with
using System.Threading.Tasks;
public async Task< ActionResult> Index()
{
BusinessController b = new BusinessController();
await b.DoSomething();
return View();
}
Watch this example on YouTube
1.CSS
.LongText{
word-wrap:break-word;
height: 10em;
width: 20em;
overflow-y: scroll;
}
2.View
<div class="LongText">
@Html.DisplayFor(x => x.Description)
</div>
Watch this example on YouTube
1. View
@{
ViewBag.Title = "Home Page";
}
<input type="submit" value="SUBMIT" />
<input type="submit" value="CANCEL" />
@section Scripts{
<script type="text/javascript">
$(document).ready(function () {
var clickNum = 0;
jQuery('input[type=submit]').click(function (event) {
if (this.value == 'CANCEL') {
clickNum = 0;
return false;
}
if (clickNum > 0) {
alert("Wait!!!!!");
return false;
}
else {
clickNum++;
}
});
});
</script>
}
2. Controller
public ActionResult Index()
Watch this example on YouTube
1. Install NuGet
PM> Install-Package Microsoft.AspNet.WebApi.WebHost
PM> Install-Package Microsoft.AspNet.WebApi
2. Add to App_Start folder
using System.Web.Http;
namespace WebApplication17
{
public static class WebAppConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
}
}
}
3. Modify Global.asax
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Http;
namespace WebApplication17
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
WebAppConfig.Register(GlobalConfiguration.Configuration);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
4. Modify Layout file
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("~/Scripts/jquery-1.10.2.min.js")
</head>
5. Create empty controller
namespace WebApplication17.Controllers
{
public class TestController : System.Web.Http.ApiController
{
public string Get()
{
return "returning something";
}
}
}
6. Modify Home\Index file
@{
ViewBag.Title = "Home Page";
}
<script>
var url = '/api/test';
$(document).ready(function () {
$.ajax({
url: url,
async: true,
success: function (data) {
alert(data);
}
});
});
</script>
Watch this example on YouTube
To fix it replace layout file
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
with
Watch this example on YouTube
1. View - add error
<script>
var uri = '/api/test';
$(document).ready(function () {
$.ajax({
url: 'api/test',
async: true,
success: function(data){
alert(data);
},
error: function (xhr, status, error) {
debugger
}
});
});
</script>
2. Global replace
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
WebApiConfig.Register(GlobalConfiguration.Configuration);
}
with
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
WebApiConfig.Register(GlobalConfiguration.Configuration);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
Watch this example on YouTube
to fix it add to the controller
[System.Web.Http.AcceptVerbs("GET", "POST")]
[System.Web.Http.HttpGet]
so it looks like
using System.Web.Mvc;
namespace WebApplication11.Controllers
{
[RoutePrefix("api/Device")]
public class TestController : System.Web.Http.ApiController
{
[System.Web.Http.AcceptVerbs("GET", "POST")]
[System.Web.Http.HttpGet]
public string f1()
{
return "hello world";
}
public string f1(int a)
{
return (a + 1).ToString();
}
}
}
Watch this example on YouTube
public ActionResult Index()
{
var b1 = IsValidEmailAddress("bob@boc.com");
var b2 = IsValidEmailAddress("Bob@bob@bob");
return View();
}
private bool IsValidEmailAddress(string email)
{
try
{
var addr = new System.Net.Mail.MailAddress(email);
return addr.Address == email;
}
catch
{
return false;
}
}
Watch this example on YouTube
Replace
[Remote(action: "ValidateSalary", controller: "Home", ErrorMessage ="will never be displayed - it will display message returned by stored procedure")]
public int Salary { get; set; }
with
[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; }
Watch this example on YouTube
[RegularExpression (@"^[^*<>a]*$", ErrorMessage = " invalid")]
public string LastName { get; set; }
Watch this example on YouTube
[RegularExpression(@"^([0-9]\d*)(?:\.[05]0?)?$", ErrorMessage = " {0} contains invalid characters")]
[Display(Name = "Salary abc...")]
public Decimal Salary { get; set; }
Watch this example on YouTube
[RegularExpression(@"^([0-9]\d*)(?:\.[05]0?)?$", ErrorMessage = " {0} contains invalid characters")]
public Decimal Salary { get; set; }
Watch this example on YouTube
0x800a138f - JavaScript runtime error: Unable to get property 'unobtrusive' of undefined or null reference
In Layout replace
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/Scripts/CustomValidation.js")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
with
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/Scripts/CustomValidation.js")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
Watch this example on YouTube
@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)
@Html.TextBoxFor(x => x.LastName)
<input type="submit" value="SUBMIT" />
}
@section Scripts{
<script type="text/javascript">
$("#IsActive").change(function (evt) {
var validator = $("#FirstName").validate();
var IsValid = $("#FirstName").valid();
});
</script>
}
Watch this example on YouTube
Button value lost in Remote Validator
to fix it replace
@model ValidateOnDbSide.Models.Customer
@{ Html.EnableClientValidation();}
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "UserID" }))
{
@Html.AntiForgeryToken()
// @Html.CheckBoxFor(x => x.IsActive)
@Html.DisplayNameFor(x => x.FirstName)
@Html.TextBoxFor(x => x.FirstName)
@Html.ValidationMessageFor(x => x.FirstName)
<br />
@Html.DisplayNameFor(x => x.LastName)
@Html.TextBoxFor(x => x.LastName)
@Html.ValidationMessageFor(x => x.LastName)
<br />
@Html.DisplayNameFor(x => x.Salary)
@Html.TextBoxFor(x => x.Salary)
@Html.ValidationMessageFor(x => x.Salary)
<br />
<input type="submit" value="Submit" name="btn" />
}
with
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; }
}
}
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;
}
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) {
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>© @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" />
}
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
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
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")
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>
}
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)
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>© @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;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
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>© @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
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})
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;
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();
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;
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
}
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;
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);
}