Archive for the ‘Javascript’ Category

Creating Custom FCKeditor Combo Plugin

Tuesday, November 25th, 2008

A simple demonstration on how to create custom FCKeditor combo plugin.

Introduction:

FCKeditor is a widely used html based text editor. In an earlier post I have shown how to integrate FCKeditor in ASP.Net. You can easily create and install custom plugin for FCKeditor.

Here I have prepared a custom month combo plugin. User can select month from January to December and insert the selected month into the editor.

Complete Scenario

Description:

Step 1:

Create a folder named “monthcombo” in “\editor\plugins” folder. Create a javascript file named “fckplugin.js” in the folder “monthcombo”. Now open the “fckplugin.js” file by any editor.

Step 2:

Inititalize the month combo as follows.

// Initialize the Month Combo
var monthCombo = function (name)
{
  this.Name = name;
}

Step 3:

Create function for executing the command.

// Execute the Command
monthCombo.prototype.Execute = function(itemText, itemLabel) 
{
    if (itemText != "")
        FCK.InsertHtml("<span>" + itemText + "</span>");
}

Step 4:

Create function for managing the plugin behavior.

// Manage the plugin behavior
monthCombo.prototype.GetState = function()
{
    return FCK_TRISTATE_OFF; // FCK_TRISTATE_OFF or  FCK_TRISTATE_ON
}

Step 5:

Register the month combo command.

// Register the command.
FCKCommands.RegisterCommand( 'MonthCombo' ,  new  monthCombo('Month Combo') ) ;

Step 6:

Create the toolbar button and set its prototype as follows.

// Create the toolbar button.
var monthComboToolbar = function(tooltip,  style)
{
    this.CommandName   = 'MonthCombo';
    this.Label         = this.GetLabel();
    this.Tooltip       = tooltip?  tooltip : this.Label;
    this.Style         = style;  //FCK_TOOLBARITEM_ICONTEXT OR FCK_TOOLBARITEM_ONLYTEXT
}
 
// Set the toolbar prototype.
monthComboToolbar.prototype = new  FCKToolbarSpecialCombo;

Step 7:

Create function for the label of the toolbar that is to be appeared on the toolbar.

// Label to appear in the FCK toolbar
monthComboToolbar.prototype.GetLabel  = function()
{
    return "Month Combo";
}

Step 8:

Add items to the combo list.

//Add the items to the combo list
monthComboToolbar.prototype.CreateItems  =  function(A)
{
    var months = Array("January", "February", "March",  "April",
                       "May", "June", "July",  "August",
                       "September", "October", "November",  "December");
 
    for (var i = 0; i < months.length; i++)
    {
        this._Combo.AddItem(months[i],  months[i]);
    }
}

Step 9:

Register the combo with the FCKeditor.

//Register the combo with the FCKeditor
FCKToolbarItems.RegisterItem('MonthCombo' , new monthComboToolbar( 'Month Combo', FCK_TOOLBARITEM_ICONTEXT ) ) ; // FCK_TOOLBARITEM_ONLYICON or FCK_TOOLBARITEM_ONLYTEXT  or  FCK_TOOLBARITEM_ICONTEXT

Step 10:

Save the “fckplugin.js”. We are near the end. Now open the “fckconfig.js” file located in the root directory. Add the month combo plugin as follows:

//Add Month Combo Plugin
FCKConfig.Plugins.Add( 'monthcombo' );

Step 11:

Finally, add this combo [‘MonthCombo’] to FCKConfig.ToolbarSets["Default"] or FCKConfig.ToolbarSets["Basic"] settings as follows.

FCKConfig.ToolbarSets["Basic"] = [
	['Bold','Italic','-','OrderedList','UnorderedList','-','Link','Unlink','-','About', 'MonthCombo']
] ;

Reference:

Creating & Installing a Plugin in FCKeditor

Conclusion:

Download the plugin here. MonthCombo

convert this post to pdf.

Pagination Class for ASP.NET MVC

Wednesday, August 13th, 2008

A class for creating different types of pagination link in Asp.Net Mvc.

Pagination For Asp.Net Mvc

Pagination For Asp.Net Mvc

Introduction

I was looking for a pagination class to use in Asp.Net Mvc. I found ASP.NET MVC: PagedList<T> and ASP.NET MVC – Pagination View User Control. But I felt for an easier and customizable pagination class. I have developed many projects using CodeIgniter framework and that time I found their pagination class is pretty better and easier. So, I have decided to prepare a pagination class like this for Asp.Net Mvc.

Using the Code

Controller

In your controller, to get your current (i.e. selected) page number put this code snippet.

string pageString = "";
 
try
{
    pageString = Request.Url.Segments[3];
}
catch (Exception)
{
    pageString = null;
}
 
int page = (String.IsNullOrEmpty(pageString)) ? 1 : Int32.Parse(pageString);

Here 3 is the segment which holds the page number. It can vary as per your URL.

Then use the pagination class as shown in the following example.

Pagination pagination = new Pagination();
 
pagination.BaseUrl      = "/Users/List/";
pagination.TotalRows    = totalRows;
pagination.CurPage      = page;
pagination.PerPage      = 10;
 
string pageLinks = pagination.GetPageLinks();
 
int start   = (page - 1) * pagination.PerPage;
int offset  = pagination.PerPage;

In BaseUrl you can write full path like "http://www.sitename.com/Controller/Action/" or relative path like "/Controller/Action/". Here "start" is the number from which row should be counted and "offset" is the number of rows should be returned. “totalRows” is the total number of rows.

Now you can use this "pageLinks" string which is the generated page link.

Next, set your data in the ViewData like the following.

ViewData["title"]       = "Pagination in Asp.Net Mvc";
ViewData["totalRows"]   = totalRows;
ViewData["result"]      = result;
ViewData["pageLinks"]   = pageLinks;

Here, "totalRows" is the total number of rows and "result" is the desired resultset.

View

In view page, you can show the page link as follows:

<% if ((string)ViewData["pageLinks"] != "")
   { %>
   <%= ViewData["pageLinks"] %>
   <br /><br />
<% } %>

Model

You can create a model and make two methods to get total rows and the data from table using LINQ, as shown in the following example.

public int GetTotalUsers()
{
    return new MyDataContext().Users.Count();
}
 
public List GetUsers(int start, int offset)
{
    var users = new MyDataContext().Users.Skip(start)
                                                 .Take(offset);
 
    return users.ToList();
}

Configuration Settings

General Properites
BaseUrl Full or relative URL to the controller/action (Mandatory).
TotalRows Total number of rows in your resultset (Mandatory).
CurPage Current page number, default 1 (Mandatory).
PerPage Number of items you want to show per page (Optional).
NumLinks Number of “digit” links before and after the current page number (Optional).
ItemType Item type enumeration value (Optional).
Link Properites
FirstLink The text to be shown in the “first” link on the left.
NextLink The text to be shown in the “next” page link.
PrevLink The text to be shown in the “previous” page link.
LastLink The text to be shown in the “last” link on the right.
Tag Properties
FullTagOpen The opening tag placed on the left side of the entire result.
FullTagClose The closing tag placed on the right side of the entire result.
FirstTagOpen The opening tag for the “first” link.
FirstTagClose The closing tag for the “first” link.
LastTagOpen The opening tag for the “last” link.
LastTagClose The closing tag for the “last” link.
CurTagOpen The opening tag for the “current” link.
CurTagClose The closing tag for the “current” link.
NextTagOpen The opening tag for the “next” link.
NextTagClose The closing tag for the “next” link.
PrevTagOpen The opening tag for the “previous” link.
PrevTagClose The closing tag for the “previous” link.
NumTagOpen The opening tag for the “digit” link.
NumTagClose The closing tag for the “digit” link.
ItemTagOpen The opening tag for the “Item”.
ItemTagClose The closing tag for the “Item”.

You can set configuration settings in three ways.

1. Set as regular property is set. Example:

objPagination.PerPage  = 10;
objPagination.PrevLink = "Prev";
objPagination.NextLink = "Next";

2. Put a Pagination.xml file in "Content" folder and create object of Pagination class as:

Pagination objPagination = new Pagination(true);

Pagination.xml file should be as following pattern as example.

<?xml version="1.0" encoding="utf-8" ?>
<Pagination>
    <NumLinks><![CDATA[5]]></NumLinks>
    <FullTagOpen><![CDATA[<p class='pagination'>]]></FullTagOpen>
    <FullTagClose><![CDATA[</p>]]></FullTagClose>
    <CurTagOpen><![CDATA[<span class='current'>]]></CurTagOpen>
    <CurTagClose><![CDATA[</span>]]></CurTagClose>
</Pagination>

3. Create a any xml file like the above Pagination.xml file and call the method LoadPaginationXml with the file full path as argument. Example:

objPagination.LoadPaginationXml("C:\MyProject\MyPagination.xml");

Different types of pagination

By this pagination class you can build different types of page link for your page. Just call the method GetPageLinks with your desired PaginationType as argument. Example:

objPagination.GetPageLinks(PaginationType.FirstPreviousNextLastItemRight);

If you want to display item set item type as follows:

objPagination.ItemType = ItemTypes.Page;

Conclusion

I think thats enough to use this pagination class easily. Bye for this time.

Download

You can download the Pagination class from here.

PaginationClass

You can download sample project from here.

PaginationInAspNetMvc

convert this post to pdf.

Integrating FCKeditor in ASP.Net

Sunday, July 20th, 2008

Introduction

In Basic ASP.Net, FCKeditor can be easily integrated. Here is the link where I found that. http://docs.fckeditor.net/FCKeditor_2.x/Developers_Guide/Integration/ASP.NET

However, to integrate FCKeditor in ASP.Net MVC environment, we have to follow some tricky steps. Here I will show how to integrate using core javascript as well as using Jquery.

Using Javascript:

Step 1

Download the FCKeditor from http://www.fckeditor.net/download.

Step 2

Unzip the package and put in your project content directory. I liked to make a directory “Javascript” under “Content” directory and put “unzipped fckeditor” here. I have also put fckeditorapi.js in “Javascript” folder. You can get more information on FCKeditor API here

http://docs.fckeditor.net/FCKeditor_2.x/Developers_Guide/JavaScript_API

Step 3

I have added a MVC view file in Home folder and named it as “Fck.aspx”. To view this file, I included a method in HomeController, as follows.

/// <summary>
/// Show FCK Editor View Page
/// </summary>
public void Show()
{
    RenderView("Fck");
}

Step 4

In Fck.aspx, include the fckeditor.js and fckeditorapi.js file:

<script type="text/javascript" src="../../Content/Javascript/fckeditor/fckeditor.js"></script>
<script type="text/javascript" src="../../Content/Javascript/fckeditorapi.js"></script>

Include the following to replace textarea (named ‘content’) by FCKeditor. Here I have included InsertContent(), ShowContent() and ClearContent() methods to perform some extra actions.

<script type="text/javascript">
window.onload = function()
{
    var oFCKeditor = new FCKeditor( 'content' ) ;
    oFCKeditor.BasePath = "/Content/Javascript/fckeditor/" ;
    oFCKeditor.Height = 300;
    oFCKeditor.ReplaceTextarea() ;
}
 
function InsertContent()
{
    var oEditor = FCKeditorAPI.GetInstance('content') ;
    var sample = document.getElementById("sample").value;
    oEditor.InsertHtml(sample);
}
 
function ShowContent()
{
    var oEditor = FCKeditorAPI.GetInstance('content') ;
    alert(oEditor.GetHTML());
}
 
function ClearContent()
{
    var oEditor = FCKeditorAPI.GetInstance('content');
    oEditor.SetHTML("");
}
</script>

Here is the html content:

<div>
  <input id="sample" type="text" />
  <input id="cmdInsert" type="button" value="Insert Content" onclick="InsertContent()" />

  <input id="cmdClear" type="button" value="Clear Content" onclick="ClearContent()" />
  <br /> <br />
  <textarea id="content" cols="30" rows="10"></textarea>
  <br />
  <input id="cmdShow" type="button" value="Show Content" onclick="ShowContent()" />
</div>

Step 5

Now build the application and run. Click the “FCK Editor” link and get the result.

FCKEditor in ASP.Net

Using JQuery

Step 1

Download jquery from http://www.jquery.com. I have put jquery-1.2.6.pack.js and jquery.FCKEditor.js in my “Javascript” folder”.

Step 2

I have added a MVC view file in Home folder and named it as “FckJquery.aspx”. To view this file, I included a method in HomeController, as follows.

/// <summary>
/// Show FCK Editor By JQuery
/// </summary>
public void View()
{
    RenderView("FckJquery");
}

Step 3

In FckJquery.aspx, include the jquery-1.2.6.pack.js, fckeditor.js and jquery.FCKEditor.js file:

<script type="text/javascript" src="../../Content/Javascript/jquery-1.2.6.pack.js"></script>
<script type="text/javascript" src="../../Content/Javascript/fckeditor/fckeditor.js"></script>
<script type="text/javascript" src="../../Content/Javascript/jquery.FCKEditor.js"></script>

Include the following to replace textarea (named ‘content’) by FCKeditor. Here I have included InsertContent(), ShowContent() and ClearContent() methods to perform some extra actions.

<script type="text/javascript">
$(document).ready(function(){
    $.fck.config = {path: '/Content/Javascript/fckeditor/', height: 300 };
    $('textarea#content').fck();
});
 
function InsertContent()
{
    var sample = document.getElementById("sample").value;
    $.fck.insertHtml('fck1', sample);
}
 
function ShowContent()
{
    alert($.fck.content('fck1', ''));
}
 
function ClearContent()
{
    $.fck.clearHtml('fck1');
}
</script>

Here is the html content:

<div>
  <input id="sample" type="text" />
  <input id="cmdInsert" type="button" value="Insert Content" onclick="InsertContent()" />

  <input id="cmdClear" type="button" value="Clear Content" onclick="ClearContent()" />
  <br /> <br />
  <textarea id="content" cols="30" rows="10"></textarea>
  <br />
  <input id="cmdShow" type="button" value="Show Content" onclick="ShowContent()" />
</div>

Step 4

In jquery.FCKEditor.js file, I have included two functions. Function insertHtml() inserts html content into fckeditor and clearHtml() clears the content.

// insert Html Content
insertHtml: function(i, v) {
  try{
    var x = FCKeditorAPI.GetInstance(i);
 
    if(v) x.InsertHtml(v);
    else return '';
  }
  catch(e) { return ''; };
},
 
// clear Html Content
clearHtml: function(i) {
  try{
    var x = FCKeditorAPI.GetInstance(i);
 
    x.SetHTML('');
  }
  catch(e) { return ''; };
},

Step 5

Now build the application and run. Click the “FCK Editor By JQuery” link and get the result. Enjoy It!

Source Code

Here is the source code FCKeditorMvcDemo

References

http://docs.fckeditor.net

http://www.jquery.com

http://www.fyneworks.com/jquery/FCKEditor

Conclusion

Next I will try to give some demonstration on how to build plugins in FCKeditor. Till then bye.

convert this post to pdf.