Chủ Nhật, 7 tháng 7, 2013

JQuery DataTables Editable in Asp.net c#


Asp.Net How To Edit JQuery DataTables Using Asp.Net GridView , C#

The purpose of this article is to show how you can implement JQuery DataTables   with Asp.net Gridview Control. The jQuery DataTables plugin is an excellent client-side component. This plugin adds lots of functionalities to the plain HTML tables that are placed in web pages such as  sorting, searching, pagination, changing page length etc

HTML Markup:
Here you will see in html markup theres a pencil image which on click becomes editable  and so user can edit the values also look at classname .i.e set classname as update_ + id  using string.Concat().   where id is  database rowId.

<asp:GridView ID="myGridview" runat="server" BackColor="White"   AutoGenerateColumns="False" CssClass="gvmyalign"    
       BorderColor="Gray" BorderStyle="Solid" BorderWidth="1px" CellPadding="4"  ForeColor="Black" GridLines="None" Width="500px"
       AllowPaging="True"  ShowFooter="false"  >
       <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
        <HeaderStyle BackColor="#A86E07" Font-Bold="True" ForeColor="White" />
           <Columns>
            <asp:TemplateField HeaderText="Id" Visible="false">
              <ItemTemplate>
                    <asp:Label ID="lblid" runat="server" Text='<%# Eval("Id") %>'></asp:Label>
              </ItemTemplate>
              </asp:TemplateField>
               <asp:TemplateField HeaderText="Name"   ItemStyle-Width="230">
                 <ItemTemplate>
                       <asp:Label ID="lblname" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
                 </ItemTemplate>
               </asp:TemplateField>
               <asp:TemplateField ShowHeader="False" ItemStyle-Width="90" >
               <ItemTemplate>
                 <asp:Image ID="Image1" ToolTip="Edit" style="cursor:pointer;" CssClass=' <%# string.Concat("update_",Eval("Id")) %>' ImageUrl="~/images/pencil.png" runat="server" />
                </ItemTemplate>
           </asp:TemplateField>
        </Columns>
       <PagerStyle BackColor="#A86E07" ForeColor="White" HorizontalAlign="Center" />
    <EditRowStyle BackColor="#d9d9d9" />
  <AlternatingRowStyle BackColor="White" ForeColor="#A86E07" />
</asp:GridView>

Code Behind: DefaultPage.aspx
You need to add Page_PreRender event on .cs where we set gridview's UseAccessibleHeader=true .
protected void  (object sender, EventArgs e)
{
if (myGridview.Rows.Count > 0) {
myGridview.UseAccessibleHeader = true;
myGridview.HeaderRow.TableSection = TableRowSection.TableHeader;
}
}

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

public void gvBind() {
myGridview.EmptyDataText = "No Record";
DataTable dt = getData();
myGridview.DataSource = dt;
myGridview.DataBind();
}

Now the Real coding part comes here using JQuery Datatables .
Add JqueryDatable Script Files 
<link href="jquery.dataTables_themeroller.css" rel="stylesheet" type="text/css" />
<script src="../js/jquery.dataTables.js" type="text/javascript"></script>
<script src="../js/jquery.dataTables.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var oTable;
$(".gvmyalign span").contents().unwrap();
oTable = $(".gvmyalign").dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers"

});
});
</script>
Now after apply JQuery DataTable Gridview look like below image. ScreenShot:
Now:


Edit Mode:


Edit Row:On Click of pencil image we convert Lable into Textboxes and place it inside JQueryDatables which we stored using variable oTable. Here on EDIT mode we replace pencil image with SAVE and CANCEL image button, also set respected ids into classes as same we did for pencil img. On cancle img click we Undo editmode, when the user finishes editing an click Save img button a AJAX call is sent to the server-side page that updates the records into database. Also u need to check some JQuery Datatable's method which have used like fnUpdate(),  fnDraw(),  fnGetData(nRow);

Client Side:

<script type="text/javascript">

var oTable;
function editRow(oTable, nRow) {
var aData = oTable.fnGetData(nRow);
var jqTds = $('>td', nRow);
var gtval = aData[1];
var absValue = $("#hdid").val();
var mySav_Class = absValue.replace('update_', 'sav_');
var myCnl_Class = absValue.replace('update_', 'cnl_');
var sname = $("#hdname").val();

jqTds[0].innerHTML = '<input class="edt1" type="text" value="' + sname + '">';
jqTds[1].innerHTML = '<img class="' + mySav_Class + '" title="Save" src="save.png" /><img class="' + myCnl_Class + '" title="Cancel" src="cancle.png" />';
}

function restoreRow(oTable, nRow) {
var aData = oTable.fnGetData(nRow);
var jqTds = $('>td', nRow);
for (var i = 0, iLen = jqTds.length; i < iLen; i++) {
oTable.fnUpdate(aData[i], nRow, i, false);
}
oTable.fnDraw();
}

function updatevalidDatarow() {
if ($('.edt1').val() == "") {
alert("Enter name.");
return false
}
return true;
}

$(document).ready(function () {

//One Pencil Img click make it editable mode
var nEditing = null;
$("img[class^='update_']").live('click', function (event) {
event.preventDefault;
var getId = $(this).attr("class");
$("#hdid").val(getId); // hdid is hidden field
var nRow = $(this).parents('tr')[0];
var setName = $.trim($(this).closest('tr').find('td').eq(0).text());
$("#hdname").val(setName); // hdname is hidden field

if (nEditing !== null && nEditing != nRow) {
restoreRow(oTable, nEditing);
editRow(oTable, nRow);
nEditing = nRow;
}
else {
editRow(oTable, nRow);
nEditing = nRow;
}
});

//On cancle Img click undo editable mode ie not editable
$("img[class^='cnl_']").live('click', function (event) {
var abc = $(this).attr("class");
var datetxt = $("#hdname").val();
$('.edt1').replaceWith(datetxt);
var arr = [];
arr = abc.split('_');
var id = arr[1];
var updateclass = "update_" + id;
var updatebtn = '<img src="pencil.png" style="cursor:pointer;" title="Edit" class="' + updateclass + '">';
$('.' + abc).replaceWith(updatebtn);
$('.sav_' + id).replaceWith("");
});


//On save Img Click update Query fire and saves the record into database.
$("img[class^='sav_']").live('click', function (event) {
var s = $(this).attr('class');
var arr = [];
arr = s.split('_');
var id = arr[1];
var updateclass = "update_" + id;
var updatebtn = '<img src="pencil.png" title="Edit" style="cursor:pointer;" class="' + updateclass + '">';
var upName = $(".edt1").val();
var dataString = id+"="+upName;
var nposition = $(this).closest("td").get(0);
var aPosition = oTable.fnGetPosition(nposition);

if (updatevalidDatarow()) {

$.ajax({
type: "POST",
url: "ajax_function/updatefn.asmx/updateName",
data: "{ 'prefix': '" + dataString + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var success = data.d;
if (success == "Record Updated") {
alertify.alert("Record is updated successfully.");
$('.edt1').replaceWith(upName);
$('.' + s).replaceWith(updatebtn);
$('.cnl_' + id).replaceWith("");
nEditing = null;
oTable.fnUpdate(upName, aPosition[0], 0, false);
oTable.fnDraw();
}
},
error: OnErrorCall
});
}
});
function OnErrorCall(response) {
alert(response.statusText);
}

$(".gvmyalign span").contents().unwrap();
oTable = $(".gvmyalign").dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers"

});
});
</script>

Server Side: 

Code Behind : updatefn.asmx 
In updatefn.asmx  we have a WebMethod  updateName(), whicih fires Update query and return result stuatus. which we will display as resulting message on ajax call of success.
[WebMethod]
public string[] updateName(string prefix)
{
List d = new List();
string resultmessage = "";
string[] value = prefix.Split('=');
int update_id = Convert.ToInt32(value[0]);
string update_name = value[1];
int result = updateIndustry_Query(update_id, update_name);
if (result > 0)
{ resultmessage = "Record Updated"; }

d.Add(string.Format("{0}",resultmessage));
return d.ToArray();
}



Không có nhận xét nào:

Đăng nhận xét