Using $.ajax to Build your SharePoint Portal Home Page

This article is a quick reference for me and my colleagues  🙂

1- add a Reference to Jquery

2 – Create handler in your webapp dll with this functions

private const string XML_START_TAG = “<?xml version=\”1.0\” encoding=\”utf-8\” ?>”;


public void ProcessRequest(HttpContext context)
if (context.Request[“op”] != null)
switch (context.Request[“op”])
case “LoadGeneralList”:
if (context.Request[“siteUrl”] != null && context.Request[“listName”] != null && context.Request[“viewName”] != null)
GetListItems(context.Request[“siteUrl”].ToString(), context.Server.UrlDecode(context.Request[“listName”].ToString()), context.Server.UrlDecode(context.Request[“viewName”].ToString()), context);

/// <summary>

/// Get List Items from for displaying on home page

/// </summary>

/// <param name=”siteUrl”>the url of the site which main domain like news</param>

/// <param name=”listName”>list name of items</param>

/// <param name=”viewName”>view name</param>

/// <param name=”context”>current web context</param>

private void GetListItems(string siteUrl, string listName, string viewName, HttpContext context)


StringBuilder sbXml = new StringBuilder();




using (SPSite site = new SPSite(string.Format(“{0}{1}”, SPContext.Current.Web.Url, siteUrl)))


using (SPWeb web = site.OpenWeb())


DataTable dt =   web.Lists[listName].GetItems(web.Lists[listName].Views[viewName]).GetDataTable();

if (dt != null)


// get data table as xml element

XElement xml = new XElement(“Items”,    dt.AsEnumerable().Select(row =>

new XElement(“Item”, dt.Columns.Cast<DataColumn>().Select(col =>

new XAttribute(col.ColumnName, row[col])









catch (Exception ex)


sbXml.AppendFormat(“<Error>{0}</Error>”, ex.ToString());





context.Response.ContentType = “text/xml”;





3  – Build your dll and put it in the GAC or project bin and put the handler file into your folder in _Layouts Folder

4- add id to the html section to use it in the script to inject the content

5- in your common script file for the project

// start ready event
$(document).ready(function () {




// load Latest new from news site
function LoadLatestNews() {
// word html
var word_html = ”;
var page_url = ‘#’;
type: “GET”,
contentType: “text/xml”,
url: “/_LAYOUTS/MyProject/Scripts/MyHandler.ashx?op=LoadGeneralList&siteUrl=/news&listName=” + encodeURI(pagesFolderName) + “&viewName=” + encodeURI(LatestNewsViewName),
dataType: ‘xml’,
async: true,
success: function (xml) {
if (xml != null && $(xml).find(‘Items’).length > 0) {
var i = 0;
$(xml).find(‘Item’).each(function () {

word_html += ‘<li class=”cloned”>’;
word_html += $(this).attr(“PublishingRollupImage”);
word_html += ‘<div class=”news_title”>’ + $(this).attr(“Title”) + ‘</div><br >’;
word_html += ‘<a href=”/news/Pages/’ + $(this).attr(“FileLeafRef”) + ‘”>المزيد</a></div>’;

word_html += ‘<a href=”/news/” class=”more”>أرشيف الأخبار</a>’;

error: function (XMLHttpRequest, textStatus, errorThrown) {
if (raiseError)
alert(textStatus + “: (” + XMLHttpRequest.statusText + “)”);

6 – Save your script file add a reference to it

7- Refresh and enjoy it 🙂


Thanks to Ahmed Gouda


SharePoint: How To Deal With People Picker Sharepoint Control into your Custom Control


In Many Cases you need to make a control to pick up a user from your user management system – Active Directory – Database Membership and so on, PeopleEditor Control make this you will say how to use it in my custom development,look

1)  Add Refernce to your HTML

<%@ Register Tagprefix=”SP” Namespace=”Microsoft.SharePoint.WebControlsAssembly=”Microsoft.SharePoint, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c” %>

2) Use it in the right position into your design

SelectionSet=”User” />

3) Get Values from it into your code behind 

PickerEntity pe = (PickerEntity)userPicker.Entities[0];  //get the first user in list
string username = pe.Description; //get username of the selected user

string DisplayName = pe.DisplayText ; //get user display name first last….


Sharepoint: How To Deal With Custom List [Add,Search]

Hi Guys, this article depends on your knowledge of what’s the concept of SharePoint List,so I already created a list called Employees under my subsite with the following columns:






so the first task that we want to do is adding new list item to the Employees List,here is the Code for this target:

you will need the following namespace:

using Microsoft.SharePoint;

//to open the site 

using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                    if (site != null)

                                                       //to open the site ….. assuming that the list will be in the same subsite

                        using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ServerRelativeUrl))
                            SPList list = web.Lists["Employees"];
                            if (list != null)
 //Create New Empty List Item
                                    SPListItem itemNew = list.Items.Add();
 //Filling it's fields
                                    itemNew["FirstName"] = txtFirstName.Text;
                                    itemNew["LastName"] = txtLastName.Text;
                                    itemNew["Age"] = txtAge.Text;
                                    itemNew["Department"] = ddlDepartments.SelectedItem.Text;
                                    itemNew["Salary"] = txtSalary.Text;

 // to enable you to update the list
                                    web.AllowUnsafeUpdates = true;

the second Task we need now to search and navigate between the list items, so how in your opinions, I'll say it now
look, this search will work with CAML Queries we will Create template for every search Criteria ie. in our screen we will search 
by FirstName and LastName as ex, so look at this code:

string FirstNameTemplate = string.Format("<Contains>" +
                                         "<FieldRef Name=\"FirstName\" />" +
                                          "<Value Type=\"Text\">{0}</Value>" +
                                       "</Contains>", txtFirstName.Text);

string LastNameTemplate = string.Format("<Contains>" +
 "<FieldRef Name=\"LastName\" />" +
 "<Value Type=\"Text\">{0}</Value>" +
 "</Contains>", txtLastName.Text);

string TrueCondition = "<Neq>" +
 "<FieldRef Name=\"FirstName\" />" +
 "<Value Type=\"Text\">asamir226644</Value>" + //Dummy Data

string FirstName = txtFirstName.Text != string.Empty ? FullNameTemplate : TrueCondition;
string LastName = txtLastName.Text != string.Empty ? LastNameTemplate : TrueCondition;

string CAMLQueryemplate = string.Format("<Where>" +
 "<And>" +
 "{0}" + //FirstName
 "{1}" + //LastName
 "</And>" +
 "</Where>", FirstName, LastName);

using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                    if (site != null)
                        using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ServerRelativeUrl))
                            SPList list = web.Lists["Employees"];
                            if (list != null)
                                SPQuery query = new SPQuery();
                                string str = string.Format(CAMLQueryemplate);
                                query.Query = str;
                                DataTable dataTable = list.GetItems(query).GetDataTable();
                                gvEmployees.DataSource = dataTable;

Character Counter for ASP.Net TextArea Using jQuery

javascript, js icon

<script type=“text/javascript” language=“javascript”>

var characterLimit = 150;
$(document).ready(function () {
$(‘#<%=txtMessage.ClientID %>’).bind(‘keyup’, function () {

var charactersUsed = $(this).val().length;
if (charactersUsed > characterLimit) {

charactersUsed = characterLimit;

$(this).val($(this).val().substr(0, characterLimit));


var charactersRemaining = characterLimit – charactersUsed;





html, mime, text icon

<textarea id=“txtMessage” runat=“server” ></textarea>

<br />

<span><span id=“remainingCharacters”></spancharacters remaining </span>


you can use it in comment sections or sending sms message Content

Response.End(); & Download file or Export File Problem – Solution


When we came to download a file or Export it ,we know that we write Response.End(); to end the response and save the file to our machine,but if you try any other button in the page after that you notice that it doesn’t work! unless you make Refresh to the page! so what’s the solutoin?


javascript, js icon

<script type=”text/javascript” language=”javascript”>

function ButtonWorkAgain()

{         window.WebForm_OnSubmit = function ()         { return true; };     }


folder, html icon

<asp:GridView ID=”gvFiles” runat=”server” AutoGenerateColumns=”False” EnableModelValidation=”True”>



<asp:LinkButton ID=”hlbtnDownLoad” runat=”server” onclick=”hlbtnDownLoad_Click”                                         OnClientClick=”ButtonWorkAgain();”></asp:LinkButton>