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);
break;
}
}
}

/// <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();

sbXml.Append(XML_START_TAG);

try

{

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])

))));

sbXml.Append(xml.ToString());

}

else

sbXml.Append(“<Empty></Empty>”);

}

}

}

catch (Exception ex)

{

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

}

finally

{

context.Response.ClearContent();

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

context.Response.Write(sbXml.ToString());

context.Response.End();

}

}

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 () {

LoadLatestNews();

}

 

// load Latest new from news site
function LoadLatestNews() {
// word html
var word_html = ”;
var page_url = ‘#’;
$.ajax({
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>’;
}
i++;
});

$(‘ul#latestNews’).html(word_html);
}
},
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

Advertisements

Character Counter for ASP.Net TextArea Using jQuery


javascript, js icon

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

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

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

charactersUsed = characterLimit;

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

$(this).scrollTop($(this)[0].scrollHeight);

}
var charactersRemaining = characterLimit – charactersUsed;

$(‘#remainingCharacters’).html(charactersRemaining);

});

});

</script>

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


Case:

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?

Solution:

javascript, js icon

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

function ButtonWorkAgain()

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

</script>

folder, html icon

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

<Columns>

<asp:TemplateField>

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

</asp:TemplateField>

</Columns>

</asp:GridView>

Validate File Upload Control to upload certain extensions


we will take an example to upload images only with this extensions ” jpg , jpeg , png , gif ”

<script type=“text/javascript”>

function checkImageExtension(elem) {

var filePath = elem.value;

if (filePath.indexOf(‘.’) == -1)

return false;

var validExtensions = new Array();

var ext = filePath.substring(filePath.lastIndexOf(‘.’) + 1).toLowerCase();
validExtensions[0] = ‘jpg’;

validExtensions[1] = ‘jpeg’;

validExtensions[2] = ‘png’;

validExtensions[3] = ‘gif’;
for (var i = 0; i < validExtensions.length; i++)

{

if (ext == validExtensions[i])

return true;

else

elem.value = ‘ ‘;

}

alert(ext.toString() + ‘\n’ + ‘Disabled’);

return false;

}

<asp:FileUpload ID=”fuAttachment” runat=”server” />

C#:

protected void Page_Load(object sender, EventArgs e)

{            fuSelectFile.Attributes.Add(“onchange”, “return checkImageExtension(this);”);        }

Screen shot