All posts by Thiyagu

MVC Razor : How to call controller from html radio button click event using Jquery

In this post we will discuss about how to call the controller from the radio button click event using jquery.

HTML :

<div id=”radio”>
<input type=”radio” id=”Isactive” name=”Isactive” value=”1″ >Yes</input >
<input type=”radio” id=”Isactive” name=”Isactive” value=”0″ >No</input >
</div>

JQUERY :

$(document).ready(function () {
$(‘input[type=radio]’).live(‘change’, function()
{
alert($(this).val());
window.location = ‘@Url.Action(“UserDetail”, “AllUserDetail”)’;
});

});

Controller : AllUserDetailController

public ActionResult UserDetail()
{
//Perform action here
}

Explanation:

  • window.location = ‘@Url.Action(“UserDetail”, “AllUserDetail”)’;

UserDetail : This will be the name of the action
AllUserDetail : This will be the name of the controller.

 

 

MVC – Passing JSON data from controller to the view

Passing JSON data from controller to the view

UserDetailController.cs

[HttpPost]
[ValidateInput(false)]
public JsonResult FetchUserDetailsByid(string userID)
{
List<UserDetailByID>  userDetailollection;
try
{
//return the User Details List
userDetailollection = new GetUserDetailsByidModel().FetchUserDetailByid(UserID));
}
catch (Exception ex)
{

throw ex;
}
var jsonSerializer = new JavaScriptSerializer();
string output = jsonSerializer.Serialize(userDetailollection );
return Json(new
{
output
}, JsonRequestBehavior.AllowGet);
}

Included Namespace:

using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Script.Serialization;

View (JQUERY)

$.ajax({url: “@Url.Action(“FetchUserDetailsByid”, “UserDetail”)”,
data: “{ ‘userID’: ‘” + userID + “‘ }”,
dataType: “json”,
type: “POST”,
contentType: “application/json; charset=utf-8”,
success: function(data)
{
//Converting JSON String to JSON Object
var jsonObject = $.parseJSON(data.output);
if (parseInt(jsonObject.length) > 0)
{
alert( jsonObject[0].UserName);
}
},
error: function(result) {
alert(“Error”);
}

Note :

1.  URL  “FetchUserDetailsByid” be the name of the method
             “UserDetail” be the name of the controller

2. “var jsonObject = $.parseJSON(data.output);” is used to converting
         json string to object

How to split the attribut “class” name in the html element

How to split the attribute “class” name  in the html element

HTML :

<div id=”divUserDetails” class=”red”>

JQEURY :

$(document).on(“click”, “#divUserDetails”, function()
{
var userColor = $(this).attr(‘class’) == null ? “No User Color Found” : $(this).attr(‘class’);
alert(userColor );
}

Output

Here is the output

How to get the top and left positon of clicked td/div

How to  get the  top and left positon of clicked td/div

Jquery

$(document).on(“click”, “#tbUserDetails”, function()
{
var getclickTop = $(this).offset().top;
var getclickLeft = $(this).offset().left;
}

Explanation:
.on method is used for dynamically created table using jquery (at runtime)

HTML

<table>
<tr>
<td id=’tbUserDetails’></td>
</tr>
</table>

MVC4 Razor : How to get the value from view to controller

MVC4 Razor : How to get the value from view to controller ?

Explanation :

Here i explain how to get the value from html razor control (view) to controller

Code in View:

@using (Html.BeginForm())
{
@Html.TextBox(“txtCustomerName”)
<input type=”submit” value=”Send” />
}

Code in Controller

[AcceptVerbs(HttpVerbs.Post)] public ActionResult Index1(FormCollection collection)
{
string customerName = collection[“txtCustomerName”].ToString();
return null;
}

Output :

After press send button the value will be catch in controller (as like below)

Note :
As above , we can get value of other control from the view to controller
1. [AcceptVerbs(HttpVerbs.Post)] , will do action when we use Html.BeginForm()
2. FormCollection : It provides to access  the values that were just posted to your page.

create user control and how to use from toolbar

Let we saw how to create user control and how to use from toolbar

Step 1: Right Click and Add —> NewItem–>Usercontrol.cs

Step 2: Click “Ok” , And Place the Collection of controls to make a group

Step 3: Make compile after every changes in UserControl, After successful Build, the Usercontrol created in Tool box.

Step 4 : Now drag and drop the User Control to the .aspx

Create Captcha using DLL

Here we discuss about how to create Captcha using DLL

.aspx File

<%@ Register Assembly=”MSCaptcha” Namespace=”MSCaptcha” TagPrefix=”cc1″ %>

<form id=”form1″ runat=”server”>
<div>
<cc1:CaptchaControl ID=”Captcha1″ runat=”server”
CaptchaBackgroundNoise=”Low” CaptchaLength=”5″
CaptchaHeight=”60″ CaptchaWidth=”200″
CaptchaLineNoise=”None” CaptchaMinTimeout=”5″
CaptchaMaxTimeout=”240″ FontColor = “#529E00″ />
</div>
<asp:TextBox ID=”txtCaptcha” runat=”server”></asp:TextBox>
<br />
<asp:Button ID=”btnVerify” runat=”server” Text=”Verify” OnClick=”btnVerify_Click” />
<asp:RequiredFieldValidator ID=”RequiredFieldValidator1″ runat=”server” ErrorMessage=”*Required” ControlToValidate = “txtCaptcha”></asp:RequiredFieldValidator>
<br />
<br />
<asp:Label ID=”lblMessage” runat=”server” Font-Names = “Arial” Text=””></asp:Label>
</form>

CodeBehind File

protected void btnVerify_Click(object sender, EventArgs e)
{
Captcha1.ValidateCaptcha(txtCaptcha.Text.Trim());
if (Captcha1.UserValidated)
{
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = “Valid”;
}
else
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = “InValid”;
}
}

Note : Download .dll here

Code shows how to zip while uploading the file.

This code shows how to zip while uploading the file.

Need to include System.IO.Compression namespace to zip the upload files. In click event write the below code.

using System.IO.Compression;
using System.IO;

protected void btnUpload_Click(object sender, EventArgs e)
{
string strName = Path.GetFileName( FileUpload1.PostedFile.FileName);
Stream myStream = FileUpload1.PostedFile.InputStream;
byte[] myBuffer = new byte[myStream.Length + 1];
myStream.Read(myBuffer, 0, myBuffer.Length);
myStream.Close();
FileStream myCompressedFile = default(FileStream);
myCompressedFile = File.Create(Server.MapPath(Path.ChangeExtension(strName, “gz”)));
GZipStream myStreamZip = new GZipStream(myCompressedFile, CompressionMode.Compress);
myStreamZip.Write(myBuffer, 0, myBuffer.Length);
myStreamZip.Close();
}

Here i am set size as +1 of upladed file size.

Custom Paging with Numbers

Custom Paging with Numbers
===========================

.aspx
======

<div>
PageSize:
<asp:DropDownList ID=”ddlPageSize” runat=”server” AutoPostBack=”true” OnSelectedIndexChanged=”PageSize_Changed”>
<asp:ListItem Text=”10″ Value=”10″ />
<asp:ListItem Text=”25″ Value=”25″ />
<asp:ListItem Text=”50″ Value=”50″ />
<asp:ListItem Text=”75″ Value=”75″ />
</asp:DropDownList>
<hr />
<asp:GridView ID=”gvCustomerDetails” runat=”server”>
</asp:GridView>
<br />
<asp:Button ID=”btnprev” Text=”<<” OnClick=”MovetoPrev” runat=”server” />
<asp:Repeater ID=”rptPage” runat=”server”>
<ItemTemplate>
<asp:LinkButton ID=”lnkPage” runat=”server” Text='<%#Eval(“Text”)%>’ CommandArgument='<%# Eval(“Value”) %>’
OnClick=”GettingPageIndex”></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
<asp:Button ID=”btnnext” Text=”>>” OnClick=”MovetoNext” runat=”server” />
</div>

.Cs
====

#region Using Namespaces
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using CustomerDetail;
using System.Web.UI.WebControls;
#endregion

public partial class gridviewpaging2 : System.Web.UI.Page
{
#region Private Constants
private const string SQL_CONNECTION = “Data Source=DBSRV;Initial Catalog=Shopping;User ID=sa;Password=sa”;
private const string SQL_SPNAME = “[sproc_GetCustomersDetails]”;
#endregion

#region Public Variables
public static Int64 page_Number = 1;
public int record_Count;
public static int PAGE_SIZE = 10;
#endregion

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadCustomerDetails();
LoadPageSize();
}
}

#region Load Customer Records
private void LoadCustomerDetails()
{
var CustomerDetails = new List<CustomerDetails>();
#region Fetching and Loading the Customer Details
try
{
using (var sqlConn = new SqlConnection(SQL_CONNECTION))
{
using (var sqlCmd = new SqlCommand(SQL_SPNAME, sqlConn))
{
sqlCmd.Parameters.AddWithValue(“@PageNo”, page_Number);
sqlCmd.Parameters.AddWithValue(“@PageSize”,PAGE_SIZE);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlConn.Open();
using (var sqlDataReader = sqlCmd.ExecuteReader())
{
while (sqlDataReader.Read())
{
CustomerDetails.Add(new CustomerDetails(Convert.ToInt32(sqlDataReader[“ID”]), Convert.ToString(sqlDataReader[“CustomerName”]),
Convert.ToString(sqlDataReader[“EmailID”]), Convert.ToString(sqlDataReader[“PhoneNo”])
));
}
sqlDataReader.NextResult();
sqlDataReader.Read();
record_Count = Convert.ToInt32(sqlDataReader[“TotalRec”]);
lbl_TNOPages.Text = ”  ” + Convert.ToInt32(sqlDataReader[“TotalPages”]); ;
}
}
gvCustomerDetails.DataSource = CustomerDetails.AsReadOnly();
gvCustomerDetails.DataBind();
lbl_TPages.Text = ”  ” + (record_Count).ToString();
lbl_CPage.Text = ”  ” + (page_Number).ToString();
lbl_RRecords.Text = ”  ” + ((record_Count) – (page_Number * PAGE_SIZE)).ToString();
EnableAndDisableButton();
}
}
catch (Exception ex)
{
throw ex;
}
#endregion
}
#endregion

#region Load PageSize in DropDown
public void LoadPageSize()
{
ddl_PageSize.Items.Add(“10”);
ddl_PageSize.Items.Add(“20”);
ddl_PageSize.Items.Add(“30”);
ddl_PageSize.Items.Add(“40”);
}
#endregion

#region Enable and Disable the Button
public void EnableAndDisableButton()
{
if (page_Number == 1)
{
btn_Previous.Enabled = false;
if (Int32.Parse(lbl_TPages.Text) > 0)
btn_Next.Enabled = true;
else
btn_Next.Enabled = false;
}
else
{
btn_Previous.Enabled = true;
if (page_Number == Int32.Parse(lbl_TPages.Text))
btn_Next.Enabled = false;
else
btn_Next.Enabled = true;
}
}
#endregion

#region Next and Previous Button Click
protected void Btn_Next_Click(object sender, EventArgs e)
{
try
{
Button btn = (Button)sender;
if (btn.Text == “Previous”)
page_Number–;
else
page_Number++;
LoadCustomerDetails();
}
catch (Exception ex)
{
throw ex;
}
}
#endregion

#region DropDown SelectedIndex Change
protected void ddl_PageSize_SelectedIndexChanged(object sender, EventArgs e)
{
PAGE_SIZE = Convert.ToInt32(ddl_PageSize.SelectedItem.Text);
LoadCustomerDetails();
}
#endregion
}

CustomerDetails.cs
==================

#region Using Namespaces
using System;
using System.Data;
using System.Configuration;
using System.Web;
#endregion

namespace CustomerDetail
{
public class ConnectionDetails
{
#region Public Method
public string ConnectionInfo
{
get
{
return ConfigurationSettings.AppSettings[“myConnectionString”].ToString();
}
}
#endregion
}

public class CustomerDetails
{
#region Private Members
private readonly int c_id;
private readonly string c_email;
private readonly string c_phoneNumber;
private readonly string c_name;
#endregion

#region Public Members
public int ID
{
get { return c_id; }
}
public string Name
{
get { return c_name; }
}
public string Email
{
get { return c_email; }
}
public string PhoneNumber
{
get { return c_phoneNumber; }
}
#endregion

#region Public Const.
public CustomerDetails(int pID, string pName, string pEmail, string pPhoneNumber)
{
c_id = pID;
c_email = pEmail;
c_name = pName;
c_phoneNumber = pPhoneNumber;
}
#endregion

}

}

Stored Procedure
================

ALTER PROCEDURE [dbo].[sproc_GetCustomersDetails]
@PageNo        INT,
@PageSize    INT
AS
BEGIN
SET NOCOUNT ON;

DECLARE @StartIndex INT, @EndIndex INT, @TotalRec INT, @TotalPages INT;

SELECT @TotalRec = COUNT(1) FROM [tCustomer] WITH (NOLOCK)
WHERE [CustomerName] IS NOT NULL;

IF @PageNo <= 0 SET @PageNo = 1;
IF @PageSize <= 0 SET @PageSize = 1;
IF @PageSize > @TotalRec SET @PageSize = @TotalRec;

SET @TotalPages = CEILING(@TotalRec * 1.0 / @PageSize);
IF (@PageNo > @TotalPages) SET @PageNo = @TotalPages;

SET @StartIndex = (@PageNo – 1) * @PageSize + 1;
SET @EndIndex =  @StartIndex + @PageSize – 1;

IF @StartIndex > @TotalRec SET @StartIndex = @TotalRec;
IF @EndIndex > @TotalRec SET @EndIndex = @TotalRec;

WITH [Customer] AS
(
SELECT ROW_NUMBER() OVER (ORDER BY [CustomerName] ASC) AS [RowNo], [ID]
FROM [tCustomer] WITH (NOLOCK)
WHERE [CustomerName] IS NOT NULL
)
SELECT
[I].[ID],
[I].[CustomerName],
[I].[EmailID],
[I].[PhoneNo]
FROM [tCustomer] AS [I] WITH (NOLOCK)
INNER JOIN [Customer] AS [II] WITH (NOLOCK) ON [II].[RowNo] BETWEEN @StartIndex AND @EndIndex AND [II].[ID] = [I].[ID]
ORDER BY [II].[RowNo] ASC;

SELECT @TotalPages AS [TotalPages], @TotalRec AS [TotalRec];
END;