Watch on YouTube:
Replace
public PartialViewResult test(){
return View();
}
with
public PartialViewResult test(){
return PartialView();
}
Monday, 22 February 2016
Monday, 15 February 2016
MSSQL - Query to list all duplicated indexes
watch this example on YouTube:
;With DupInx As (Select SCH.name as SchemaName, OBJ.name as TableName,
IDX.name as IndexName,
INDEX_COL(SCH.name + '.' + OBJ.Name, IDX.index_Id, 1) as Col1,
INDEX_COL(SCH.name + '.' + OBJ.Name, IDX.index_Id, 2) as Col2,
INDEX_COL(SCH.name + '.' + OBJ.Name, IDX.index_Id, 3) as Col3,
INDEX_COL(SCH.name + '.' + OBJ.Name, IDX.index_Id, 4) as Col4,
INDEX_COL(SCH.name + '.' + OBJ.Name, IDX.index_Id, 5) as Col5,
INDEX_COL(SCH.name + '.' + OBJ.Name, IDX.index_Id, 6) as Col6
From sys.indexes as IDX INNER JOIN sys.objects as OBJ on IDX.object_id = OBJ.object_id INNER JOIN
sys.schemas as SCH on SCH.schema_id = OBJ.schema_id
Where (IDX.index_id>0))
Select MD1.SchemaName, MD1.TableName, MD1.IndexName, MD2.IndexName As DuplicatedIndex, MD1.Col1, MD1.Col2, MD1.Col3
From DupInx as MD1 INNER JOIN DupInx as MD2 on MD1.TableName = MD2.TableName and
MD1.IndexName <> MD2.IndexName
and isnull(MD1.Col1, '') = isnull(MD2.Col1, '')
and isnull(MD1.Col2, '') = isnull(MD2.Col2, '')
and isnull(MD1.Col3, '') = isnull(MD2.Col3, '')
and isnull(MD1.Col4, '') = isnull(MD2.Col4, '')
and isnull(MD1.Col5, '') = isnull(MD2.Col5, '')
MSSQL - Check if index exists and if exists - delete it
Watch this example on YouTube
IF Exists(Select * FRom sys.indexes where name = 'IX_Customers' and object_Id = object_id('[Customers]') )
BEgin
Drop Index IX_Customers on Customers
end
IF Exists(Select * FRom sys.indexes where name = 'IX_Customers' and object_Id = object_id('[Customers]') )
BEgin
Drop Index IX_Customers on Customers
end
MSSQL - how to duplicate existing table
Watch this example on YouTube:
select * into NEWTable from ORIGINALTable
select * into NEWTable from ORIGINALTable
Friday, 12 February 2016
MVC - How to add Calendar extension to textBox
Watch this example on YouTUbe:
1. Ensure Layout.cshtml has the following at the beginning:
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("~/Scripts/jquery-1.8.2.min.js")
</head>
and the following at the end:
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryui")
@Styles.Render("~/Content/themes/base/css", "~/Content/css")
@Scripts.Render("~/Scripts/DatePicker.js")
@RenderSection("scripts", required: false)
</body>
2. Create DatePicker.js in scripts folder:
$(function () {
$('.editor-file-date').datepicker();
});
3. Now every control with with class editor-file-date will have calendar extension
1. Ensure Layout.cshtml has the following at the beginning:
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("~/Scripts/jquery-1.8.2.min.js")
</head>
and the following at the end:
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryui")
@Styles.Render("~/Content/themes/base/css", "~/Content/css")
@Scripts.Render("~/Scripts/DatePicker.js")
@RenderSection("scripts", required: false)
</body>
2. Create DatePicker.js in scripts folder:
$(function () {
$('.editor-file-date').datepicker();
});
3. Now every control with with class editor-file-date will have calendar extension
MVC - Fix error - JavaScript runtime error: Object doesn't support property or method
Watch this example on YouTube:
Replace
@Scripts.Render("~/bundles/jqueryui")
@Styles.Render("~/Content/themes/base/css", "~/Content/css")
@Scripts.Render("~/Scripts/DatePicker.js")
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
</body>
with
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryui")
@Styles.Render("~/Content/themes/base/css", "~/Content/css")
@Scripts.Render("~/Scripts/DatePicker.js")
@RenderSection("scripts", required: false)
</body>
order matters
Replace
@Scripts.Render("~/bundles/jqueryui")
@Styles.Render("~/Content/themes/base/css", "~/Content/css")
@Scripts.Render("~/Scripts/DatePicker.js")
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
</body>
with
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryui")
@Styles.Render("~/Content/themes/base/css", "~/Content/css")
@Scripts.Render("~/Scripts/DatePicker.js")
@RenderSection("scripts", required: false)
</body>
order matters
Fix error - 0x800a138f - JavaScript runtime error: Unable to get property 'checked' of undefined or null reference
Watch this example on YouTube:
To fix the following error:
0x800a138f - JavaScript runtime error: Unable to get property 'checked' of undefined or null reference
Replace
<form id="form1" runat="server">
<div>
<script language="javascript" type="text/javascript">
function AdjustControls() {
var Month = document.getElementById('<%= rbMonth.ClientID %>');
var Range = document.getElementById('<%=rbRange.ClientID %>');
if (Month[0].checked) {
alert('month checked')
}
else {
alert('month not checked')
}
}
</script>
</div>
<div class="SearchLabels">
<asp:RadioButton ID="rbMonth" runat="server" Text="Month" Checked="true"
GroupName="SearchBy" onclick="AdjustControls();" />
<asp:RadioButton ID="rbRange" runat="server" Text="Range"
GroupName="SearchBy" onclick="AdjustControls();" />
</div>
</form>
with
<form id="form1" runat="server">
<div>
<script language="javascript" type="text/javascript">
function AdjustControls() {
var Month = document.getElementById('<%= rbMonth.ClientID %>');
var Range = document.getElementById('<%=rbRange.ClientID %>');
if (Month.checked) {
alert('month checked')
}
else {
alert('month not checked')
}
}
</script>
</div>
<div class="SearchLabels">
<asp:RadioButton ID="rbMonth" runat="server" Text="Month" Checked="true"
GroupName="SearchBy" onclick="AdjustControls();" />
<asp:RadioButton ID="rbRange" runat="server" Text="Range"
GroupName="SearchBy" onclick="AdjustControls();" />
</div>
</form>
To fix the following error:
0x800a138f - JavaScript runtime error: Unable to get property 'checked' of undefined or null reference
Replace
<form id="form1" runat="server">
<div>
<script language="javascript" type="text/javascript">
function AdjustControls() {
var Month = document.getElementById('<%= rbMonth.ClientID %>');
var Range = document.getElementById('<%=rbRange.ClientID %>');
if (Month[0].checked) {
alert('month checked')
}
else {
alert('month not checked')
}
}
</script>
</div>
<div class="SearchLabels">
<asp:RadioButton ID="rbMonth" runat="server" Text="Month" Checked="true"
GroupName="SearchBy" onclick="AdjustControls();" />
<asp:RadioButton ID="rbRange" runat="server" Text="Range"
GroupName="SearchBy" onclick="AdjustControls();" />
</div>
</form>
with
<form id="form1" runat="server">
<div>
<script language="javascript" type="text/javascript">
function AdjustControls() {
var Month = document.getElementById('<%= rbMonth.ClientID %>');
var Range = document.getElementById('<%=rbRange.ClientID %>');
if (Month.checked) {
alert('month checked')
}
else {
alert('month not checked')
}
}
</script>
</div>
<div class="SearchLabels">
<asp:RadioButton ID="rbMonth" runat="server" Text="Month" Checked="true"
GroupName="SearchBy" onclick="AdjustControls();" />
<asp:RadioButton ID="rbRange" runat="server" Text="Range"
GroupName="SearchBy" onclick="AdjustControls();" />
</div>
</form>
JavaScript - how to fix error - 0x800a138f - JavaScript runtime error: Unable to get property 'submit' of undefined or null reference
Watch this on YouTube:
0x800a138f - JavaScript runtime error: Unable to get property 'submit' of undefined or null reference
Replace
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScriptSubmit.aspx.cs" Inherits="WebTest.JavaScriptSubmit" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function doSomething() {
document.second.submit();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="doSomething();" />
</div>
</form>
<form method="post" action="./JavaScriptSubmit.aspx" id="second"></form>
</body>
</html>
with
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScriptSubmit.aspx.cs" Inherits="WebTest.JavaScriptSubmit" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function doSomething() {
this.form1.submit();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="doSomething();" />
</div>
</form>
<form method="post" action="./JavaScriptSubmit.aspx" id="second"></form>
</body>
</html>
0x800a138f - JavaScript runtime error: Unable to get property 'submit' of undefined or null reference
Replace
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScriptSubmit.aspx.cs" Inherits="WebTest.JavaScriptSubmit" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function doSomething() {
document.second.submit();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="doSomething();" />
</div>
</form>
<form method="post" action="./JavaScriptSubmit.aspx" id="second"></form>
</body>
</html>
with
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScriptSubmit.aspx.cs" Inherits="WebTest.JavaScriptSubmit" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function doSomething() {
this.form1.submit();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="doSomething();" />
</div>
</form>
<form method="post" action="./JavaScriptSubmit.aspx" id="second"></form>
</body>
</html>
MVC - fix Error - An object reference is required for the non-static field, method, or property
Watch this solution on YouTUbe
Replace
public static void SaveCustomer(CustomerToUpdate customer)
with
public void SaveCustomer(CustomerToUpdate customer)
Wednesday, 10 February 2016
MVC - how to update just one cell in the table after double click
Watch this example on YouTube:
1. Create the following table
CREATE TABLE [dbo].[Customers](
[CustomerID] [int] IDENTITY(1,1) NOT NULL,
[CustomerFirstName] [varchar](50) NOT NULL,
[CustomerLastName] [varchar](50) NOT NULL,
CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED
(
[CustomerID] 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 ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[Customers] ON
GO
INSERT [dbo].[Customers] ([CustomerID], [CustomerFirstName], [CustomerLastName]) VALUES (1, N'Bob3', N'Dylan1')
GO
INSERT [dbo].[Customers] ([CustomerID], [CustomerFirstName], [CustomerLastName]) VALUES (2, N'Oleh 1', N'Skrypka')
GO
INSERT [dbo].[Customers] ([CustomerID], [CustomerFirstName], [CustomerLastName]) VALUES (3, N'Frank', N'Sinatra')
GO
INSERT [dbo].[Customers] ([CustomerID], [CustomerFirstName], [CustomerLastName]) VALUES (4, N'John ', N'Lennon')
GO
INSERT [dbo].[Customers] ([CustomerID], [CustomerFirstName], [CustomerLastName]) VALUES (5, N'Mick ', N'Jagger')
GO
SET IDENTITY_INSERT [dbo].[Customers] OFF
GO
2. First Stored Procedure
Create PROCEDURE [dbo].[GetAllCustomers]
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
Select * From Customers
END
3. Second Stored Procedure
CREATE PROCEDURE [dbo].[GetCustomerByCustomerID]
@CustomerID int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
Select * From Customers Where CustomerID = @CustomerID
END
4. Third Stored Procedure
CREATE PROCEDURE [dbo].[UpdateCustomers]
@CustomerID int,
@CustomerFirstName varchar(50),
@CustomerLastName varchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
Update Customers Set CustomerFirstName = @CustomerFirstName, CustomerLastName = @CustomerLastName
Where CustomerID = @CustomerID
END
5. Index.cshtml
@model IEnumerable<MvcApplication4.Models.Customer>
@{
ViewBag.Title = "Index";
}
@section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$(".CustomerFirstName").dblclick(function (e) {
e.stopPropagation();
var CurrentEle = $(this);
var value = $(this).html();
var row = $(e.target).closest('tr');
var CustomerID = row.find($("[id*=key]")).val();
UpdateVal(CurrentEle, value, CustomerID, "CustomerFirstName");
});
$(".CustomerLastName").dblclick(function (e) {
e.stopPropagation();
var CurrentEle = $(this);
var value = $(this).html();
var row = $(e.target).closest('tr');
var CustomerID = row.find($("[id*=key]")).val();
UpdateVal(CurrentEle, value, CustomerID, "CustomerLastName");
});
});
function UpdateVal(CurrentEle, value, CustomerID, ColumnToUpdate){
if($(".cellValue") !== undefined){
if($(".cellValue").val() !== undefined){
$(".cellValue").parent().html($("#OriginalValue").val().trim());
$(".cellValue").remove();
}
}
if(value.match("<") == null){
$(CurrentEle).html('<div class="cellValue" id="cellWrapper"> ' +
'<input class="cellValue" type="text" id="txtValue" value="'+ value + '" />' +
'<input class="cellValue" type="hidden" value="' + CustomerID + '" id="keySelected" />' +
'<input class="cellValue" type="hidden" value="' + ColumnToUpdate + '" id="ColumnToUpdate" /> ' +
'<input class="cellValue" type="hidden" value="' + value + '" id="OriginalValue" /> ' +
'<input class="cellValue" type="button" value="save" onclick="return SaveChanges()" /> ' +
'<input class="cellValue" type="button" value="cancel" onclick="return CancelChanges()" /> ' +
'</div> ');
}
$(".cellValue").focus();
$(".cellValue").keyup(function(event){
if(event.keyCode == 13){
$(CurrentEle).html($(".cellValue").val().trim());
}
});
}
function CancelChanges(e){
if($(".cellValue")!== undefined){
if($(".cellValue").val() !== undefined){
$(".cellValue").parent().html($("#OriginalValue").val().trim());
$(".cellValue").remove();
}
}
window.location.reload();
}
function SaveChanges(e) {
var customer = {};
customer.ColumnToUpdate = $("[id*=ColumnToUpdate]").val();
customer.FieldValue = $("[id*=txtValue]").val();
customer.ID = $("[id*=keySelected]").val();
$.ajax({
type: "POST",
url: "Cust/SaveCustomer",
data: '{customer: ' + JSON.stringify(customer) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response){
alert("done!!");
location.href = location.href;
window.location.reload();
}
});
}
</script>
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th></th>
<th>
@Html.DisplayNameFor(model => model.CustomerFirstName)
</th>
<th>
@Html.DisplayNameFor(model => model.CustomerLastName)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.HiddenFor(modelItem => item.CustomerID, new { id = "key"})
</td>
<td>
<div class="CustomerFirstName">@Html.DisplayFor(modelItem => item.CustomerFirstName)</div>
</td>
<td>
<div class="CustomerLastName">@Html.DisplayFor(modelItem => item.CustomerLastName)</div>
</td>
</tr>
}
</table>
6. Cust Controller
public class CustomerToUpdate
{
public int ID { get; set; }
public string FieldValue { get; set; }
public string ColumnToUpdate { get; set; }
}
public class CustController : Controller
{
private TESTEntities db = new TESTEntities();
public void SaveCustomer(CustomerToUpdate customer)
{
cust upd = db.GetCustomerByCustomerID(customer.ID).First();
switch (customer.ColumnToUpdate)
{
case "CustomerFirstName":
upd.CustomerFirstName = customer.FieldValue;
break;
case "CustomerLastName":
upd.CustomerLastName = customer.FieldValue;
break;
default:
break;
}
db.UpdateCustomers(upd.CustomerID, upd.CustomerFirstName, upd.CustomerLastName);
}
public ActionResult Index()
{
return View(db.Customers.ToList());
}
7. Route.config
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Cust", action = "Index", id = UrlParameter.Optional }
);
}
8. add the following to layout file
@Scripts.Render("~/Scripts/jquery-1.8.2.js")
@Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.js")
</head>
1. Create the following table
CREATE TABLE [dbo].[Customers](
[CustomerID] [int] IDENTITY(1,1) NOT NULL,
[CustomerFirstName] [varchar](50) NOT NULL,
[CustomerLastName] [varchar](50) NOT NULL,
CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED
(
[CustomerID] 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 ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[Customers] ON
GO
INSERT [dbo].[Customers] ([CustomerID], [CustomerFirstName], [CustomerLastName]) VALUES (1, N'Bob3', N'Dylan1')
GO
INSERT [dbo].[Customers] ([CustomerID], [CustomerFirstName], [CustomerLastName]) VALUES (2, N'Oleh 1', N'Skrypka')
GO
INSERT [dbo].[Customers] ([CustomerID], [CustomerFirstName], [CustomerLastName]) VALUES (3, N'Frank', N'Sinatra')
GO
INSERT [dbo].[Customers] ([CustomerID], [CustomerFirstName], [CustomerLastName]) VALUES (4, N'John ', N'Lennon')
GO
INSERT [dbo].[Customers] ([CustomerID], [CustomerFirstName], [CustomerLastName]) VALUES (5, N'Mick ', N'Jagger')
GO
SET IDENTITY_INSERT [dbo].[Customers] OFF
GO
2. First Stored Procedure
Create PROCEDURE [dbo].[GetAllCustomers]
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
Select * From Customers
END
3. Second Stored Procedure
CREATE PROCEDURE [dbo].[GetCustomerByCustomerID]
@CustomerID int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
Select * From Customers Where CustomerID = @CustomerID
END
4. Third Stored Procedure
CREATE PROCEDURE [dbo].[UpdateCustomers]
@CustomerID int,
@CustomerFirstName varchar(50),
@CustomerLastName varchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
Update Customers Set CustomerFirstName = @CustomerFirstName, CustomerLastName = @CustomerLastName
Where CustomerID = @CustomerID
END
5. Index.cshtml
@model IEnumerable<MvcApplication4.Models.Customer>
@{
ViewBag.Title = "Index";
}
@section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$(".CustomerFirstName").dblclick(function (e) {
e.stopPropagation();
var CurrentEle = $(this);
var value = $(this).html();
var row = $(e.target).closest('tr');
var CustomerID = row.find($("[id*=key]")).val();
UpdateVal(CurrentEle, value, CustomerID, "CustomerFirstName");
});
$(".CustomerLastName").dblclick(function (e) {
e.stopPropagation();
var CurrentEle = $(this);
var value = $(this).html();
var row = $(e.target).closest('tr');
var CustomerID = row.find($("[id*=key]")).val();
UpdateVal(CurrentEle, value, CustomerID, "CustomerLastName");
});
});
function UpdateVal(CurrentEle, value, CustomerID, ColumnToUpdate){
if($(".cellValue") !== undefined){
if($(".cellValue").val() !== undefined){
$(".cellValue").parent().html($("#OriginalValue").val().trim());
$(".cellValue").remove();
}
}
if(value.match("<") == null){
$(CurrentEle).html('<div class="cellValue" id="cellWrapper"> ' +
'<input class="cellValue" type="text" id="txtValue" value="'+ value + '" />' +
'<input class="cellValue" type="hidden" value="' + CustomerID + '" id="keySelected" />' +
'<input class="cellValue" type="hidden" value="' + ColumnToUpdate + '" id="ColumnToUpdate" /> ' +
'<input class="cellValue" type="hidden" value="' + value + '" id="OriginalValue" /> ' +
'<input class="cellValue" type="button" value="save" onclick="return SaveChanges()" /> ' +
'<input class="cellValue" type="button" value="cancel" onclick="return CancelChanges()" /> ' +
'</div> ');
}
$(".cellValue").focus();
$(".cellValue").keyup(function(event){
if(event.keyCode == 13){
$(CurrentEle).html($(".cellValue").val().trim());
}
});
}
function CancelChanges(e){
if($(".cellValue")!== undefined){
if($(".cellValue").val() !== undefined){
$(".cellValue").parent().html($("#OriginalValue").val().trim());
$(".cellValue").remove();
}
}
window.location.reload();
}
function SaveChanges(e) {
var customer = {};
customer.ColumnToUpdate = $("[id*=ColumnToUpdate]").val();
customer.FieldValue = $("[id*=txtValue]").val();
customer.ID = $("[id*=keySelected]").val();
$.ajax({
type: "POST",
url: "Cust/SaveCustomer",
data: '{customer: ' + JSON.stringify(customer) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response){
alert("done!!");
location.href = location.href;
window.location.reload();
}
});
}
</script>
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th></th>
<th>
@Html.DisplayNameFor(model => model.CustomerFirstName)
</th>
<th>
@Html.DisplayNameFor(model => model.CustomerLastName)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.HiddenFor(modelItem => item.CustomerID, new { id = "key"})
</td>
<td>
<div class="CustomerFirstName">@Html.DisplayFor(modelItem => item.CustomerFirstName)</div>
</td>
<td>
<div class="CustomerLastName">@Html.DisplayFor(modelItem => item.CustomerLastName)</div>
</td>
</tr>
}
</table>
6. Cust Controller
public class CustomerToUpdate
{
public int ID { get; set; }
public string FieldValue { get; set; }
public string ColumnToUpdate { get; set; }
}
public class CustController : Controller
{
private TESTEntities db = new TESTEntities();
public void SaveCustomer(CustomerToUpdate customer)
{
cust upd = db.GetCustomerByCustomerID(customer.ID).First();
switch (customer.ColumnToUpdate)
{
case "CustomerFirstName":
upd.CustomerFirstName = customer.FieldValue;
break;
case "CustomerLastName":
upd.CustomerLastName = customer.FieldValue;
break;
default:
break;
}
db.UpdateCustomers(upd.CustomerID, upd.CustomerFirstName, upd.CustomerLastName);
}
public ActionResult Index()
{
return View(db.Customers.ToList());
}
7. Route.config
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Cust", action = "Index", id = UrlParameter.Optional }
);
}
8. add the following to layout file
@Scripts.Render("~/Scripts/jquery-1.8.2.js")
@Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.js")
</head>
Tuesday, 9 February 2016
ASP.NET - GridView - edit cell after double click
In this example - I will save changes to the database after double clicking cell in gridview.
1. Create the following table
CREATE TABLE [dbo].[Customers](
[CustomerID] [int] IDENTITY(1,1) NOT NULL,
[CustomerFirstName] [varchar](50) NOT NULL,
[CustomerLastName] [varchar](50) NOT NULL,
CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED
(
[CustomerID] 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 ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[Customers] ON
GO
INSERT [dbo].[Customers] ([CustomerID], [CustomerFirstName], [CustomerLastName]) VALUES (1, N'Bob3', N'Dylan1')
GO
INSERT [dbo].[Customers] ([CustomerID], [CustomerFirstName], [CustomerLastName]) VALUES (2, N'Oleh 1', N'Skrypka')
GO
INSERT [dbo].[Customers] ([CustomerID], [CustomerFirstName], [CustomerLastName]) VALUES (3, N'Frank', N'Sinatra')
GO
INSERT [dbo].[Customers] ([CustomerID], [CustomerFirstName], [CustomerLastName]) VALUES (4, N'John ', N'Lennon')
GO
INSERT [dbo].[Customers] ([CustomerID], [CustomerFirstName], [CustomerLastName]) VALUES (5, N'Mick ', N'Jagger')
GO
SET IDENTITY_INSERT [dbo].[Customers] OFF
GO
2. First Stored Procedure
Create PROCEDURE [dbo].[GetAllCustomers]
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
Select * From Customers
END
3. Second Stored Procedure
CREATE PROCEDURE [dbo].[GetCustomerByCustomerID]
@CustomerID int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
Select * From Customers Where CustomerID = @CustomerID
END
4. Third Stored Procedure
CREATE PROCEDURE [dbo].[UpdateCustomers]
@CustomerID int,
@CustomerFirstName varchar(50),
@CustomerLastName varchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
Update Customers Set CustomerFirstName = @CustomerFirstName, CustomerLastName = @CustomerLastName
Where CustomerID = @CustomerID
END
5. here is my customers class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace WebApplication12
{
public class Customers
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class CustomerDA
{
private SqlConnection connection;
private string connectionString = Convert.ToString(System.Configuration.ConfigurationManager.ConnectionStrings["SQLConnectionString"]);
private SqlCommand command;
private SqlDataAdapter adapter;
private DataSet dataset;
public DataSet GetAllCustomers()
{
try
{
adapter = default(SqlDataAdapter);
connection = new SqlConnection(connectionString);
command = new SqlCommand("GetAllCustomers", connection);
dataset = new DataSet();
adapter = new SqlDataAdapter(command);
adapter.Fill(dataset);
return dataset;
}
finally
{
if (connection.State != ConnectionState.Closed)
{
connection.Close();
connection.Dispose();
}
if (command != null)
{
command.Dispose();
}
}
}
public DataSet GetCustomerByCustomerID(String ID)
{
try
{
adapter = default(SqlDataAdapter);
connection = new SqlConnection(connectionString);
command = new SqlCommand("GetCustomerByCustomerID", connection);
command.Parameters.Add("@CustomerID", SqlDbType.Int);
command.Parameters["@CustomerID"].Value = Convert.ToInt32(ID);
dataset = new DataSet();
command.CommandType = CommandType.StoredProcedure;
adapter = new SqlDataAdapter(command);
adapter.Fill(dataset);
return dataset;
}
finally
{
if (connection.State != ConnectionState.Closed)
{
connection.Close();
connection.Dispose();
}
if (command != null)
{
command.Dispose();
}
}
}
public Customers UpdateCustomer(Customers c)
{
command = new SqlCommand("UpdateCustomers");
try
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@CustomerID", SqlDbType.Int);
command.Parameters.Add("@CustomerFirstName", SqlDbType.VarChar, 50);
command.Parameters.Add("@CustomerLastName", SqlDbType.VarChar, 50);
command.Parameters["@CustomerID"].Value = c.ID;
command.Parameters["@CustomerFirstName"].Value = c.FirstName;
command.Parameters["@CustomerLastName"].Value = c.LastName;
using (connection = new SqlConnection(connectionString))
{
command.Connection = connection;
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}
catch(Exception ex){
//handle exception
}
return c;
}
}
}
6. HTML file
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication12.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".CustomerFirstName").dblclick(function (e) {
e.stopPropagation();
var currentEle = $(this);
var value = $(this).html();
var row = $(e.target).closest('tr');
var CustomerID = row.find($("[id*=key]")).val();
UpdateVal(currentEle, value, CustomerID, "CustomerFirstName");
});
$(".CustomerLastName").dblclick(function (e) {
e.stopPropagation();
var currentEle = $(this);
var value = $(this).html();
var row = $(e.target).closest('tr');
var CustomerID = row.find($("[id*=key]")).val();
UpdateVal(currentEle, value, CustomerID, "CustomerLastName");
});
});
function UpdateVal(CurrentEle, value, CustomerID, ColumnToUpdate) {
if ($(".cellValue") !== undefined) {
if ($(".cellValue").val() !== undefined) {
$(".cellValue").parent().html($("#OriginalValue").val().trim());
$(".cellValue").remove();
}
if (value.match("<") == null) {
$(CurrentEle).html('<div class="cellValue" id"cellWrapper"> ' +
' <input class="cellValue" type="text" id="txtValue" value="' + value + '" />' +
' <input class="cellValue" type="hidden" value="' + CustomerID + '" id="keySelected" />' +
' <input class="cellValue" type="hidden" value="' + ColumnToUpdate + '" id="ColumnToUpdate" />' +
' <input class="cellValue" type="hidden" value="' + value + '" id="OriginalValue" />' +
' <input class="cellValue" type="button" value="Save" id="btnSave" onClick="return SaveChanges()" />' +
' <input class="cellValue" type="button" value="Cancel" id="btnCancel" onClick="return CancelChanges()" /> ' +
' </div> ');
}
$(".cellValue").focus();
$(".cellValue").keyup(function (event) {
if (event.keyCode == 13) {
$(CurrentEle).html($(".cellValue").val().trim());
}
});
}
}
function CancelChanges(e) {
if ($(".cellValue") !== undefined) {
if ($(".cellValue").val() !== undefined) {
$(".cellValue").parent().html($("#OriginalValue").val().trim());
$(".cellValue").remove();
}
}
window.location.reload();
}
function SaveChanges(e) {
var customer = {};
customer.ColumnToUpdate = $("[id*=ColumnToUpdate]").val();
customer.FieldValue = $("[id*=txtValue]").val();
customer.ID = $("[id*=keySelected]").val();
$.ajax({
type: "POST",
url: "WebForm1.aspx/SaveCustomer",
data: '{customer: ' + JSON.stringify(customer) + '}',
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (response) {
alert("saved!");
location.href = location.href;
window.location.reload();
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="key" runat="server" Value='<%# Eval("CustomerID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label ID="Label1" CssClass="CustomerFirstName" runat="server" Text='<%# Bind("CustomerFirstName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label ID="Label2" CssClass="CustomerLastName" runat="server" Text='<%# Bind("CustomerLastName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
7. code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.Services;
using System.Web.Script.Services;
namespace WebApplication12
{
public class CustomerToUpdate
{
public int ID { get; set; }
public string FieldValue { get; set; }
public string ColumnToUpdate { get; set; }
}
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = LoadData();
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected DataTable LoadData()
{
CustomerDA usr = new CustomerDA();
return usr.GetAllCustomers().Tables[0];
}
[WebMethod]
[ScriptMethod]
public static void SaveCustomer(CustomerToUpdate customer)
{
Customers upd = new Customers();
CustomerDA da = new CustomerDA();
DataSet ds = da.GetCustomerByCustomerID(customer.ID.ToString());
upd.FirstName = (string)ds.Tables[0].Rows[0]["CustomerFirstName"];
upd.LastName = (string)ds.Tables[0].Rows[0]["CustomerLastName"];
upd.ID = (int)ds.Tables[0].Rows[0]["CustomerID"];
switch (customer.ColumnToUpdate)
{
case "CustomerFirstName":
upd.FirstName = customer.FieldValue;
break;
case "CustomerLastName":
upd.LastName = customer.FieldValue;
break;
default:
break;
}
upd = da.UpdateCustomer(upd);
}
}
}
Wednesday, 3 February 2016
MSSQL - fix error - The statement terminated. The maximum recursion 100 has been exhausted before statement completion.
Watch this example on YouTube:
to fix the following error
The statement terminated. The maximum recursion 100 has been exhausted before statement completion.
replace
;with c as (
select 1 as i
union all
select i + 1
from c
where i < 150
)
select * from c
with
;with c as (
select 1 as i
union all
select i + 1
from c
where i < 150
)
select * from c
option (maxrecursion 0)
to fix the following error
The statement terminated. The maximum recursion 100 has been exhausted before statement completion.
replace
;with c as (
select 1 as i
union all
select i + 1
from c
where i < 150
)
select * from c
with
;with c as (
select 1 as i
union all
select i + 1
from c
where i < 150
)
select * from c
option (maxrecursion 0)
JavaScript - how to fix error - To display the webpage again, Internet Explorer needs to resend the information you've recently submitted. If you were making a purchase, you should click Cancel to avoid a duplicate transaction. Otherwise, click Retry to display the webpage again.
Watch this example on YouTube:
error
To display the webpage again, Internet Explorer needs to resend the information you've recently submitted. If you were making a purchase, you should click Cancel to avoid a duplicate transaction. Otherwise, click Retry to display the webpage again.
to fix it add the following
location.href = location.href;
before
windows.location.relode();
error
To display the webpage again, Internet Explorer needs to resend the information you've recently submitted. If you were making a purchase, you should click Cancel to avoid a duplicate transaction. Otherwise, click Retry to display the webpage again.
to fix it add the following
location.href = location.href;
before
windows.location.relode();
Tuesday, 2 February 2016
Excel - Macro - how to get table from the web using VBA
Watch this example on YouTube
The following macro will put table to active sheet from the following web page:
http://localhost:50006/WebForm1.aspx
Sub GetWebTable()
With ActiveSheet.QueryTables.Add(Connection:="URL;http://localhost:50006/WebForm1.aspx", Destination:=Range("a1"))
.Refresh BackgroundQuery:=False
.SaveData = True
End With
End Sub
The following macro will put table to active sheet from the following web page:
http://localhost:50006/WebForm1.aspx
Sub GetWebTable()
With ActiveSheet.QueryTables.Add(Connection:="URL;http://localhost:50006/WebForm1.aspx", Destination:=Range("a1"))
.Refresh BackgroundQuery:=False
.SaveData = True
End With
End Sub
visual studio 2013 lost toolbar
In case you lost toolbar items on your vs2013- reinstall ajax toolkit to get toolbar back
Subscribe to:
Posts (Atom)