How to Use Only One MVC Controller For Entire Application? - model-view-controller

Is it possible Single Controller for Entire MVC Application to Route Views Or can we Rename Controller Name at Run-time to Route Views?..
i tried below code for route Views working fine.
controller:-
public class HomeController : Controller
{
public ActionResult Commmon_Method(string VN, string Id)
{
return View(#"~/" + VN + ".cshtml");
}
}
view page:
$('#btn_Test').click(function () {
window.location.href = '#Url.Action("Commmon_Method", "Home")?Id=' + 1 + '&VN=' + 'Views/Test/Index2';
});
output URL:-
http://localhost:52296/Home/Commmon_Method?Id=1&VN=Views/Test2/Index
-----------------------------*---------------------
even though i tried myself like MVC based Dynamic Route but not able to succeeded:
http://localhost:52296/Home/Test2/Index
so Controller Name should be single to supply all the request as well as i tried run-time Controller also and custom based Controller not succeed
one more thing i succeed single dynamic JSON Data method in MVC,so no need to write bundle of code to get JSON Data using Jquery Ajax method.
only thing in MVC, Single Controller based Routing Succeeded means MVC will be very Easy Development Apps, So can you Share your knowledge to Simplify the Complex Way of Development

html :-
window.location.href = '#Url.Action("common_dll", "Home")?ctrl=Test';
Controller method to create Controller:
public ActionResult common_dll(string ctrl)
{
StringBuilder sb = new StringBuilder();
sb.Append("using System;" + Environment.NewLine);
sb.Append("using System.Collections.Generic;" + Environment.NewLine);
sb.Append("using System.Data;" + Environment.NewLine);
sb.Append("using System.Data.SqlClient;" + Environment.NewLine);
sb.Append("using System.Dynamic;" + Environment.NewLine);
sb.Append("using System.Linq;" + Environment.NewLine);
sb.Append("using System.Text;" + Environment.NewLine);
sb.Append("using System.Web.Mvc;" + Environment.NewLine);
sb.Append("namespace Testing_MVC.Controllers" + Environment.NewLine);
sb.Append("{" + Environment.NewLine);
sb.Append("public class " + ctrl + "Controller" + " : Controller" + Environment.NewLine);
sb.Append("{" + Environment.NewLine);
sb.Append("public ActionResult Index()" + Environment.NewLine);
sb.Append("{" + Environment.NewLine);
sb.Append("return View();" + Environment.NewLine);
sb.Append("}" + Environment.NewLine);
sb.Append("}" + Environment.NewLine);
sb.Append("}" + Environment.NewLine);
var dir = Server.MapPath("~\\Controllers");
var file = System.IO.Path.Combine(dir, ctrl + "Controller" + ".cs");
System.IO.Directory.CreateDirectory(dir);
System.IO.File.WriteAllText(file, sb.ToString());
return this.RedirectToAction("Index", ctrl, new { id = 1 });
}

public static string JS_NAS(DataSet dss)
{
string str = Newtonsoft.Json.JsonConvert.SerializeObject(dss, Newtonsoft.Json.Formatting.Indented);
return str;
}
public static SqlParameter[] NAS_SQLPRM(string paramstr)
{
#region
string[] parameters = paramstr.Split('~');
string err = string.Empty;
int len = parameters.Length;
SqlParameter[] sqlParam = new SqlParameter[len];
for (int i = 0; i < len; i++)
{
string[] paramWithValue = parameters[i].Split('$');
string param = paramWithValue[0].ToString();
string value = paramWithValue[1].ToString();
sqlParam[i] = new SqlParameter { ParameterName = param, Value = value };
}
return sqlParam;
#endregion
}
[WebMethod]
public static String Insertupdates(string paramstr, string procname)
{
string err = "", dbstr = "";
string[] parameters = paramstr.Split('~');
int len = parameters.Length;
SqlParameter[] sqlParam = new SqlParameter[len];
for (int i = 0; i < len; i++)
{
string[] paramWithValue = parameters[i].Split('$');
string param = paramWithValue[0].ToString();
string value = paramWithValue[1].ToString();
sqlParam[i] = new SqlParameter { ParameterName = param, Value = value };
}
string str = new clsiCMSBLBase().insertData(ref err, ref dbstr, sqlParam, procname);
return err.Replace("$", "") + "$" + dbstr.Replace("$", "");
}
[WebMethod]
public static String GetRowData_Tables(string procedureName, string paramstr)
{
string[] parameters = paramstr.Split('~');
string err = string.Empty;
int len = parameters.Length;
SqlParameter[] sqlParam = new SqlParameter[len];
for (int i = 0; i < len; i++)
{
string[] paramWithValue = parameters[i].Split('$');
string param = paramWithValue[0].ToString();
string value = paramWithValue[1].ToString();
sqlParam[i] = new SqlParameter { ParameterName = param, Value = value };
}
try
{
DataSet ds = new clsiCMSBLBase().GetListData(ref err, sqlParam, procedureName);
String JSONString = String.Empty;
JSONString = Newtonsoft.Json.JsonConvert.SerializeObject(ds, Newtonsoft.Json.Formatting.Indented);
return JSONString;
}
catch (Exception)
{
return "Error";
}
}
var data = getRowData_TableBased('DBSP_ListSupplierGroup', paramstr);
function create_Listgrid(data) {
var cellsrenderer = function (row, column, value) {
return '<div style="text-align: right; margin-top: 5px;">' + (1 + row) + '</div>';
}
$("#jqxgrid").jqxGrid(
{
width: '98%',
height: '370px',
source: { datatype: "json", datafields: [], localdata: data },
filterable: true,
sortable: true,
theme: 'energyblue',
pageable: true,
columnsresize: true,
pagesizeoptions: ['5', '10', '15', '20', '100'],
pagesize: 15,
pagermode: 'default',
enabletooltips: true,
columns: get_cols(data)
/*
columns: [
{ text: 'S.No', dataField: 'Slno', align: 'left', width: '40px', cellsrenderer: cellsrenderer },
{ text: 'MapID', dataField: 'MapID', align: 'left', hidden: true },
{ text: 'PriSupplierID', dataField: 'PriSupplierID', align: 'left', hidden: true },
{ text: "Primary Supp Code", datafield: "PriSuppCode", cellsalign: 'left', align: 'left', width: '140px' },
{ text: "Primary Supplier Name", datafield: "PriSupName", cellsalign: 'left', align: 'left', width: '420px' },
{ text: "Primary Supplier Type", datafield: "PriSupType", cellsalign: 'left', align: 'left', width: '125px', hidden: true },
{ text: 'SecSupplierID', dataField: 'SecSupplierID', align: 'left', hidden: true },
{ text: "Secondary Supplier Code", datafield: "SecSuppCode", cellsalign: 'left', align: 'left', width: '190px' },
{ text: "Secondary Supplier Name", datafield: "SecSupName", cellsalign: 'left', align: 'left', width: '420px' },
{ text: "SecSupType", datafield: "SecSupType", cellsalign: 'left', align: 'left', hidden: true }
]
*/
});
}
function get_cols(data) {
var datacols = new Array();
if (!isEmpty(data) && data.Table1.length > 0) {
$.each(data.Table1, function (name, v) {
if (v.ColumnWidth == 0)
datacols.push({ text: v.ColumnHeader, datafield: v.DataField, hidden: true });
else
datacols.push({ text: v.ColumnHeader, datafield: v.DataField, cellsalign: 'left', align: 'left', width: v.ColumnWidth });
});
$("#<%=btnExport.ClientID%>").show();
}
return datacols;
}
function getRowData_TableBased(procName, paramstr) {
var rowData;
$.ajax({
url: 'Supplier_Group.aspx/GetRowData_Tables',
type: "POST",
dataType: "json",
async: false,
data: "{procedureName: '" + procName + "',paramstr: '" + paramstr + "'}",
contentType: "application/json; charset=utf-8",
success: function (data) {
var response = data.d;
if (response != "Error") {
rowData = $.parseJSON(response);
}
else {
alert("Retrive Error !!");
}
},
error: function (error) { }
});
return rowData;
}
/*
var paramstr = '';
paramstr = "#UserID$" + uid + '~';
paramstr += "#PageName$" + pgnm + '~';
*/
paramstr += "#MethodName$" + pgnm + '~';
paramstr += "#ErrorMsg$" + msg;
function fncCompareDates1(startDate, endDate) {
startDate = startDate.split('/');
endDate = endDate.split('/');
var new_start_date = new Date(startDate[2], startDate[1], startDate[0]);
var new_end_date = new Date(endDate[2], endDate[1], endDate[0]);
var date1 = startDate.split('/')[2] + "-" + startDate.split('/')[1] + "-" + startDate.split('/')[0];
var new_start_date = new Date(date1);
var date2 = endDate.split('/')[2] + "-" + endDate.split('/')[1] + "-" + endDate.split('/')[0];
var new_end_date = new Date(date2);
if (date_format(startDate) > date_format(endDate))
return false;
return true;
}
public static DataSet BIZ_LIST_DATA(ref string errString, SqlParameter[] parameters, string spname)
{
try
{
DataSet ds = new DataSet();
ds = DB_LIST_DATA(parameters, spname);
return ds;
}
catch (Exception ex)
{
errString = ex.Message;
}
return null;
}
public static DataSet DB_LIST_DATA(SqlParameter[] Params, string spName)
{
SqlConnection sqlCon = new SqlConnection(main.connectionStringICane());
try
{
DataSet ds = new DataSet();
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = sqlCon;
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = spName;
foreach (SqlParameter p in Params)
{
if ((p.Direction == ParameterDirection.InputOutput) && (p.Value == null))
{
p.Value = DBNull.Value;
}
sqlCmd.Parameters.Add(p);
}
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCmd);
sqlDataAdapter.Fill(ds);
return ds;
}
catch (Exception ex)
{
throw ex;
}
finally
{
sqlCon.Close();
sqlCon.Dispose();
}
}
function get_cols(data) {
var datacols = [];
if (!isEmpty(data)) {
$.each(data.Table1, function (name, value) {
if (value.ColumnWidth == 0)
datacols.push({ text: value.ColumnHeader, datafield: value.DataField, hidden: true });
else
datacols.push({ text: value.ColumnHeader, datafield: value.DataField, cellsalign: 'left', align: 'left', width: value.ColumnWidth });
});
}
return datacols;
}
function isEmpty(str) {
return typeof str == 'string' && !str.trim() || typeof str == 'undefined' || str === null || str == 0 || str == "" || str == "[]";
}
function getRowData_TableBased(procName, paramstr, urlpath) {
var rowData = '';
$.ajax({
url: urlpath,
type: "POST",
dataType: "json",
async: false,
data: "{procedureName: '" + procName + "',paramstr: '" + paramstr + "'}",
contentType: "application/json; charset=utf-8",
success: function (data) {
rowData = data;
},
error: function (error) {
}
});
return rowData;
}
function Common_grid() {
var commonModuleOption = {
width: '97%',
height: '350',
filterable: true,
sortable: true,
theme: 'energyblue',
pageable: true,
columnsresize: true,
pagesizeoptions: ['5', '10', '15', '20', '100'],
pagesize: 15,
pagermode: 'default',
enabletooltips: true,
};
return commonModuleOption;
}

public ActionResult Commmon_Method(string VN, string Id)
{
return View(#"~/" + VN + ".cshtml");
}
public ActionResult Commmon_Method_Url()
{
return PartialView(#"~/" + Request.QueryString["VN"] + ".cshtml");
}
[HttpPost]
public ActionResult GetRowData_Tables(string paramstr, string procedureName)
{
#region
string[] parameters = paramstr.Split('~');
string err = string.Empty;
int len = parameters.Length;
SqlParameter[] sqlParam = new SqlParameter[len];
for (int i = 0; i < len; i++)
{
string[] paramWithValue = parameters[i].Split('$');
string param = paramWithValue[0].ToString();
string value = paramWithValue[1].ToString();
sqlParam[i] = new SqlParameter { ParameterName = param, Value = value };
}
return Content(Newtonsoft.Json.JsonConvert.SerializeObject(GetListData(ref err, sqlParam, procedureName), Newtonsoft.Json.Formatting.Indented));
#endregion
}
public DataSet GetListData(ref string errString, SqlParameter[] parameters, string spname)
{
#region
try
{
DataSet ds = new DataSet();
ds = ListData(parameters, spname);
return ds;
}
catch (Exception ex)
{
errString = ex.Message;
}
return null;
#endregion
}
public DataSet ListData(SqlParameter[] Params, string spName)
{
#region
String conString = System.Configuration.ConfigurationManager.ConnectionStrings["Connection2"].ConnectionString;
SqlConnection sqlCon = new SqlConnection(conString);
#region
try
{
DataSet ds = new DataSet();
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = sqlCon;
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = spName;
foreach (SqlParameter p in Params)
{
if ((p.Direction == ParameterDirection.InputOutput) && (p.Value == null))
{
p.Value = DBNull.Value;
}
sqlCmd.Parameters.Add(p);
}
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCmd);
sqlDataAdapter.Fill(ds);
return ds;
}
catch (Exception ex)
{
throw ex;
}
finally
{
sqlCon.Close();
sqlCon.Dispose();
}
#endregion
#endregion
}
//[OutputCache(Duration = 3600, VaryByParam = "none")]
public ActionResult LoadMenus()
{
#region
#region
var cntent = "";
DataSet dsmenus = new DataSet();
string error = "";
SqlParameter[] parameters = { new SqlParameter("#usid", SqlDbType.Int) { Value = 6 } };
dsmenus = new DALModel().populateDataSet(ref error, parameters, "DBSP_Get_Menu");
StringBuilder sb = new StringBuilder();
#endregion
sb.Append("<ul id='main-menu' class='sm sm-vertical sm-blue' data-smartmenus-id='15544681331245752'>");
if (dsmenus.Tables[0].Rows[0]["MenuID"].ToString() == "0" && dsmenus.Tables[0].Rows[0]["ParentID"].ToString() == "0")
{
cntent = "<ul></ul>";
}
else
{
#region
var ds = dsmenus.Tables[0].AsEnumerable().Where(r => r.Field<Int32>("ParentID") == Convert.ToInt32("0"));
foreach (DataRow pdr in ds)
{
var MenuID = Convert.ToInt32(pdr["MenuID"].ToString());
var Action = pdr["Action"].ToString();
var Controller = pdr["Controller"].ToString();
var MenuDesc = pdr["MenuDesc"].ToString();
sb.Append("<li>");
if (Action == "")
sb.Append("<a href='#'>" + MenuDesc + "</a>");
else
//sb.Append("<a href='" + Url.Action(Action, Controller, new { MenuId = MenuID }) + "'>" + "" + MenuDesc + "" + "</a>");
sb.Append("<a href='" + Url.Action("Commmon_Method_Url", "Home", new { VN = Action, ID = MenuID }) + "'>" + "" + MenuDesc + "" + "</a>");
sb = getSubMenuList(MenuID, dsmenus, sb);
sb.Append("</li>");
}
#endregion
}
sb.Append("</ul>");
cntent = sb.ToString();
return Content(cntent, "text/html");
#endregion
}
[OutputCache(Duration = 3600, VaryByParam = "none")]
public StringBuilder getSubMenuList(Int32 ParentID, DataSet ds, StringBuilder sb)
{
#region
try
{
var sm = ds.Tables[0].AsEnumerable().Where(r => r.Field<Int32>("ParentID") == ParentID);
Int32 cnt = sm.AsDataView<DataRow>().Count;
if (cnt > 0)
{
#region
sb.Append("<ul>");
foreach (DataRow subdr in sm)
{
var MenuID = Convert.ToInt32(subdr["MenuID"].ToString());
var Action = subdr["Action"].ToString();
var Controller = subdr["Controller"].ToString();
string MenuDesc = subdr["MenuDesc"].ToString().Replace(" ", "-");
sb.Append("<li>");
if (Action == "")
sb.Append("<a href='#'>" + MenuDesc + "</a>");
else
//sb.Append("<a href='" + Url.Action(Action, Controller, new { MenuId = MenuID }) + "'>" + MenuDesc + "</a>");
sb.Append("<a href='" + Url.Action("Commmon_Method_Url", "Home", new { VN = Action, ID = MenuID }) + "'>" + MenuDesc + "</a>");
sb = getSubMenuList(MenuID, ds, sb);
sb.Append("</li>");
}
sb.Append("</ul>");
#endregion
}
else
{
return sb;
}
}
catch (Exception ex)
{
throw ex;
}
return sb;
#endregion
}
public ActionResult common_dll(string ctrl, string View)
{
#region
StringBuilder sb = new StringBuilder();
sb.Append("using System;" + Environment.NewLine);
sb.Append("using System.Collections.Generic;" + Environment.NewLine);
sb.Append("using System.Data;" + Environment.NewLine);
sb.Append("using System.Data.SqlClient;" + Environment.NewLine);
sb.Append("using System.Dynamic;" + Environment.NewLine);
sb.Append("using System.Linq;" + Environment.NewLine);
sb.Append("using System.Text;" + Environment.NewLine);
sb.Append("using System.Reflection;" + Environment.NewLine);
sb.Append("using System.Reflection.Emit;" + Environment.NewLine);
sb.Append("using System.Web.Mvc;" + Environment.NewLine);
sb.Append("namespace Testing_MVC.Controllers" + Environment.NewLine);
sb.Append("{" + Environment.NewLine);
sb.Append("public class " + ctrl + "Controller" + " : Controller" + Environment.NewLine);
sb.Append("{" + Environment.NewLine);
sb.Append("public ActionResult " + View + "()" + Environment.NewLine);
sb.Append("{" + Environment.NewLine);
sb.Append("return View();" + Environment.NewLine);
sb.Append("}" + Environment.NewLine);
sb.Append("}" + Environment.NewLine);
sb.Append("}" + Environment.NewLine);
#endregion
#region
var dir = Server.MapPath("~\\Controllers");
var file = System.IO.Path.Combine(dir, ctrl + "Controller" + ".cs");
/*
System.IO.FileInfo fi = new System.IO.FileInfo(file);
System.IO.StreamWriter str = fi.CreateText();
str.WriteLine(sb.ToString());
str.Close();
*/
//System.IO.Directory.CreateDirectory(dir);
//System.IO.File.WriteAllText(file, sb.ToString());
if (System.IO.File.Exists(file))
System.IO.File.Delete(file);
System.IO.File.AppendAllLines(file, sb.ToString().Split(Environment.NewLine.ToCharArray()).ToList<string>());
/*
System.IO.FileInfo fi = new System.IO.FileInfo(file);
System.IO.StreamWriter str = fi.CreateText();
str.WriteLine(sb.ToString());
str.Close();
*/
#endregion
return this.RedirectToAction(View, ctrl, new { MainID = 12, ID = 1 });
}

<script>
$('#btn_Test').click(function () {
window.location.href = '#Url.Action("common_dll", "Home")?ctrl=Testing&View=Index';
//window.location.href = '#Url.Action("Commmon_Method", "Home")?Id=' + 1 + '&VN=' + 'Areas/Testing/Views/Index';
});
</script>
<script>
//$(function () {
// var paramstr = '';
// paramstr = "##Month$" + 1;
// paramstr += "~##Year$" + 2018;
// paramstr += "~##StateID$" + 0;
// paramstr += "~##HubID$" + 0;
// paramstr += "~##BranchID$" + 0;
// paramstr += "~##EmpID$" + 0;
// paramstr += "~##EmpTypeID$" + 0;
// paramstr += "~##UserID$" + 1;
// paramstr += "~##UserTypeID$" + 1;
// var data = getRowData_TableBased('DBSP_MM_Rpt_AttendanceMonthWsie', paramstr, '#Url.Action("GetRowData_Tables", "Home")');
// Grid(data);
//});
function Grid(data) {
if (!isEmpty(data)) {
//$("#jqxgrid").jqxGrid($.extend(true, {}, Common_grid(), {
// source: { datatype: "json", datafields: [], localdata: data },
// columns: Get_Colmns(data)
//}));
}
}
function Get_Colmns(data) {
var datacols = [];
if (!isEmpty(data)) {
$.each(data.Table1, function (name, value) {
if (value.ColumnWidth == 0)
datacols.push({ text: value.ColumnHeader, datafield: value.DataField, hidden: true });
else
datacols.push({ text: value.ColumnHeader, datafield: value.DataField, cellsalign: 'left', align: 'left', width: value.ColumnWidth });
});
}
return datacols;
}
</script>

<script>
$('#btn_Controller1').click(function () {
window.location.href = '#Url.Action("common_dll", "Home")?ctrl=Testing&View=Index';
//window.location.href = '#Url.Action("Commmon_Method", "Home")?Id=' + 1 + '&VN=' + 'Views/Test/Index';
//window.location.href = '#Url.Action("common_dll", "Home")?ctrl=List&View=Index';
});
$('#btn_Controller2').click(function () {
window.location.href = '#Url.Action("common_dll", "Home")?ctrl=MyDocs&View=Test';
});
$('#btn_Controller3').click(function () {
window.location.href = '#Url.Action("common_dll", "Home")?ctrl=Test&View=Delete';
});
$('#btn_Controller4').click(function () {
window.location.href = '#Url.Action("common_dll", "Home")?ctrl=Test1&View=Index';
});
$('#btn_Controller5').click(function () {
window.location.href = '#Url.Action("common_dll", "Home")?ctrl=Test2&View=Index';
});
$('#btn_Controller6').click(function () {
window.location.href = '#Url.Action("common_dll", "Home")?ctrl=Test3&View=Index';
});
</script>

Related

Getting a 500 Internal Server Error Jquery

While everything is running in the software, I get this error when I make a selection from the dropdown list in only one part. Where am I making a mistake? or is it a server error?
I have not received this error in any Laravel before. When trying to get something from a dropdown list, this error comes to the console and there is no reaction on the site.
https://prnt.sc/vaujzf
<script type="text/javascript">
$("ul#product").siblings('a').attr('aria-expanded','true');
$("ul#product").addClass("show");
$("ul#product #adjustment-create-menu").addClass("active");
var lims_product_array = [];
var product_code = [];
var product_name = [];
var product_qty = [];
$('.selectpicker').selectpicker({
style: 'btn-link',
});
$('#lims_productcodeSearch').on('input', function() {
var warehouse_id = $('#warehouse_id').val();
temp_data = $('#lims_productcodeSearch').val();
if (!warehouse_id) {
$('#lims_productcodeSearch').val(temp_data.substring(0, temp_data.length - 1));
alert('Please select Warehouse!');
}
});
$('select[name="warehouse_id"]').on('change', function() {
var id = $(this).val();
$.get('getproduct/' + id, function(data) {
lims_product_array = [];
product_code = data[0];
product_name = data[1];
product_qty = data[2];
$.each(product_code, function(index) {
lims_product_array.push(product_code[index] + ' (' + product_name[index] + ')');
});
});
});
var lims_productcodeSearch = $('#lims_productcodeSearch');
lims_productcodeSearch.autocomplete({
source: function(request, response) {
var matcher = new RegExp(".?" + $.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(lims_product_array, function(item) {
return matcher.test(item);
}));
},
response: function(event, ui) {
if (ui.content.length == 1) {
var data = ui.content[0].value;
$(this).autocomplete( "close" );
productSearch(data);
};
},
select: function(event, ui) {
var data = ui.item.value;
productSearch(data);
}
});
$("#myTable").on('input', '.qty', function() {
rowindex = $(this).closest('tr').index();
checkQuantity($(this).val(), true);
});
$("table.order-list tbody").on("click", ".ibtnDel", function(event) {
rowindex = $(this).closest('tr').index();
$(this).closest("tr").remove();
calculateTotal();
});
$(window).keydown(function(e) {
if (e.which == 13) {
var $targ = $(e.target);
if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
var focusNext = false;
$(this).find(":input:visible:not([disabled],[readonly]), a").each(function() {
if (this === e.target) {
focusNext = true;
}
else if (focusNext) {
$(this).focus();
return false;
}
});
return false;
}
}
});
$('#adjustment-form').on('submit', function(e) {
var rownumber = $('table.order-list tbody tr:last').index();
if (rownumber < 0) {
alert("Please insert product to order table!")
e.preventDefault();
}
});
function productSearch(data) {
$.ajax({
type: 'GET',
url: 'lims_product_search',
data: {
data: data
},
success: function(data) {
var flag = 1;
$(".product-code").each(function(i) {
if ($(this).val() == data[1]) {
rowindex = i;
var qty = parseFloat($('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ') .qty').val()) + 1;
$('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ') .qty').val(qty);
checkQuantity(qty);
flag = 0;
}
});
$("input[name='product_code_name']").val('');
if(flag) {
var newRow = $("<tr>");
var cols = '';
cols += '<td>' + data[0] + '</td>';
cols += '<td>' + data[1] + '</td>';
cols += '<td><input type="number" class="form-control qty" name="qty[]" value="1" required step="any" /></td>';
cols += '<td class="action"><select name="action[]" class="form-control act-val"><option value="-">{{trans("file.Subtraction")}}</option><option value="+">{{trans("file.Addition")}}</option></select></td>';
cols += '<td><button type="button" class="ibtnDel btn btn-md btn-danger">{{trans("file.delete")}}</button></td>';
cols += '<input type="hidden" class="product-code" name="product_code[]" value="' + data[1] + '"/>';
cols += '<input type="hidden" class="product-id" name="product_id[]" value="' + data[2] + '"/>';
newRow.append(cols);
$("table.order-list tbody").append(newRow);
rowindex = newRow.index();
calculateTotal();
}
}
});
}
function checkQuantity(qty) {
var row_product_code = $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('td:nth-child(2)').text();
var action = $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.act-val').val();
var pos = product_code.indexOf(row_product_code);
if ( (qty > parseFloat(product_qty[pos])) && (action == '-') ) {
alert('Quantity exceeds stock quantity!');
var row_qty = $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.qty').val();
row_qty = row_qty.substring(0, row_qty.length - 1);
$('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.qty').val(row_qty);
}
else {
$('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.qty').val(qty);
}
calculateTotal();
}
function calculateTotal() {
var total_qty = 0;
$(".qty").each(function() {
if ($(this).val() == '') {
total_qty += 0;
} else {
total_qty += parseFloat($(this).val());
}
});
$("#total-qty").text(total_qty);
$('input[name="total_qty"]').val(total_qty);
$('input[name="item"]').val($('table.order-list tbody tr:last').index() + 1);
}
</script>

add ActionLink "Details" "Edit" "Delete" to a ajax list mvc 5

I want to have ActionLink "Details", "Edit" and "Delete" according to ID with an Ajax list, I managed to get my list out with datatable without having my columns in the script as you can see in my code, I would like to add the 3 links at the end of my table.
This is my controller:
[HttpGet]
public string Loadregistrationslist(int draw, int? start, int? length)
{
try
{
int IdFilter = 0;
string textFilter = "";
if (start == null)
{
start = 0;
}
else
{
start -= 1;
}
if (start < 1)
start = 0;
if (length == null)
{
length = 10;
}
var QueryString = HttpContext.Request.QueryString;
var orderBy = QueryString.Get("order[0][column]");
var orderByDir = QueryString.Get("order[0][dir]");
var search = QueryString.Get("search[value]");
var query = db.Registrations.Select(r => new RegistrationsList()
{
ID = r.ID,
FullName = r.LastName + " " + r.FirstName,
Email = r.Email,
BirthDate = r.BirthDate
});
if (search != null) {
int n;
search = search.Trim();
var isNumeric = int.TryParse(search, out n);
if (isNumeric)
{
IdFilter = n;
query = query.Where(x => x.ID == IdFilter);
}
else if (search != "")
{
textFilter = search;
query = query.Where(x => x.FullName.Contains(textFilter) || x.Email.Contains(textFilter));
}
}
string sortOrder = $"{orderBy}_{orderByDir.ToUpper()}";
switch (sortOrder)
{
//FullName
case "1_DESC":
query = query.OrderByDescending(s => s.FullName);
break;
case "1_ASC":
query = query.OrderBy(s => s.FullName);
break;
//Email
case "2_DESC":
query = query.OrderByDescending(s => s.Email);
break;
case "2_ASC":
query = query.OrderBy(s => s.Email);
break;
//ID
case "0_DESC":
query = query.OrderByDescending(s => s.ID);
break;
default: // ID ascending
query = query.OrderBy(s => s.ID);
break;
}
var data = query.Skip((int)start).Take((int)length).ToList<RegistrationsList>();
var lstData = new List<List<string>>();
foreach (var dataRow in data) {
var row = new List<string>() {
dataRow.ID.ToString(), dataRow.FullName, dataRow.Email, dataRow.BirthDate.ToString()
};
lstData.Add(row);
}
var recordsTotal = db.Registrations.Select(x => x.ID).Count();
var recordsFiltered = query.Count();
var response = new DataTablesResponse()
{
draw = draw,
recordsTotal = recordsTotal,
recordsFiltered = recordsFiltered,
data = lstData
};
return JsonConvert.SerializeObject(response, _jsonSerializerSettings);
}
catch (AjaxFunctionalException ex)
{
return JsonConvert.SerializeObject(new DataTablesResponse()
{
draw = draw,
recordsTotal = 0,
recordsFiltered = 0,
data = new List<List<string>>()/*,
errcode = ex.code,
errmessage = ex.Message,
errdata = ex.data*/
}, _jsonSerializerSettings);
}
catch (Exception ex)
{
return JsonConvert.SerializeObject(new DataTablesResponse()
{
draw = draw,
recordsTotal = 0,
recordsFiltered = 0,
data = new List<List<string>>()
/*code = 5000,
message = ex.Message,
data = null*/
}, _jsonSerializerSettings);
}
}
This is my ajax call:
$(document).ready(function ()
{
$("#registrationTable").DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "/Home/Loadregistrationslist",
"type": "GET",
"datatype": "json"
}
});
});
And this is my html for the table:
<table id="registrationTable" class="table table-striped dt-responsive display datatable dtr-inline" role="grid" aria-describedby="example-1_info">
<thead>
<tr>
<th>
ID
</th>
<th>
#Resource.FullName
</th>
<th>
#Resource.Email
</th>
<th class="sorting_desc_disabled sorting_asc_disabled">
#Resource.BirthDate
</th>
#*<th>
Edit
</th>
<th>
Delete
</th>*#
</tr>
</thead>
</table>
I found the solution, my controller changes a little bit, so here is my new code:
In my controller:
[HttpGet]
public string Loadregistrationslist(int draw, int? start, int? length)
{
try
{
int IdFilter = 0;
string textFilter = "";
if (start == null)
{
start = 0;
}
else
{
start -= 1;
}
if (start < 1)
start = 0;
if (length == null)
{
length = 10;
}
string orderByDir, search;
int orderByIdx;
List<string> cols = ExtractDataSortAndFilter(out orderByIdx, out orderByDir, out search);
var query = db.Registrations.Select(r => new RegistrationsList()
{
ID = r.ID,
FullName = r.LastName + " " + r.FirstName,
Email = r.Email,
BirthDate = r.BirthDate
});
if (search != null)
{
int n;
search = search.Trim();
var isNumeric = int.TryParse(search, out n);
if (isNumeric)
{
IdFilter = n;
query = query.Where(x => x.ID == IdFilter);
}
else if (search != "")
{
textFilter = search;
query = query.Where(x => x.FullName.Contains(textFilter) || x.Email.Contains(textFilter));
}
}
string sortOrder = $"{cols[orderByIdx]}_{orderByDir.ToUpper()}";
switch (sortOrder)
{
//FullName
case "FullName_DESC":
query = query.OrderByDescending(s => s.FullName);
break;
case "FullName_ASC":
query = query.OrderBy(s => s.FullName);
break;
//Email
case "Email_DESC":
query = query.OrderByDescending(s => s.Email);
break;
case "Email_ASC":
query = query.OrderBy(s => s.Email);
break;
//ID
case "ID_DESC":
query = query.OrderByDescending(s => s.ID);
break;
default: // ID ascending
query = query.OrderBy(s => s.ID);
break;
}
var data = new List<RegistrationsList>();
if (length > -1)
{
data = query.Skip((int)start).Take((int)length).ToList<RegistrationsList>();
}
else
{
data = query.Skip((int)start).ToList<RegistrationsList>();
}
/*var lstData = new List<List<string>>();
foreach (var dataRow in data) {
var row = new List<string>() {
dataRow.ID.ToString(), dataRow.FullName, dataRow.Email, dataRow.BirthDate.ToString()
};
lstData.Add(row);
}*/
var recordsTotal = db.Registrations.Select(x => x.ID).Count();
var recordsFiltered = query.Count();
var response = new DataTablesResponse()
{
draw = draw,
recordsTotal = recordsTotal,
recordsFiltered = recordsFiltered,
data = data
};
return JsonConvert.SerializeObject(response, _jsonSerializerSettings);
}
catch (AjaxFunctionalException ex)
{
return JsonConvert.SerializeObject(new DataTablesResponse()
{
draw = draw,
recordsTotal = 0,
recordsFiltered = 0,
data = new List<RegistrationsList>()/*,
errcode = ex.code,
errmessage = ex.Message,
errdata = ex.data*/
}, _jsonSerializerSettings);
}
catch (Exception ex)
{
return JsonConvert.SerializeObject(new DataTablesResponse()
{
draw = draw,
recordsTotal = 0,
recordsFiltered = 0,
data = new List<RegistrationsList>()
/*code = 5000,
message = ex.Message,
data = null*/
}, _jsonSerializerSettings);
}
}
private List<string> ExtractDataSortAndFilter(out int orderByIdx, out string orderByDir, out string search)
{
List<string> cols;
var QueryString = HttpContext.Request.QueryString;
cols = new List<string>();
string colName = null, colNamePath = "";
int colIdx = 0;
do
{
colNamePath = "columns[" + colIdx + "][data]";
colName = QueryString.Get(colNamePath);
cols.Add(colName);
colIdx++;
} while (colName != null);
string orderBy = QueryString.Get("order[0][column]");
orderByDir = QueryString.Get("order[0][dir]");
search = QueryString.Get("search[value]");
orderByIdx = orderBy == null ? 0 : int.Parse(orderBy);
orderByDir = orderByDir == null ? "asc" : orderByDir;
search = search == null ? "" : search;
return cols;
}
and this is my script:
$(document).ready(function () {
$("#registrationTable").DataTable({
"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
"processing": true,
"serverSide": true,
"ajax": {
"url": "/Home/Loadregistrationslist",
"type": "GET",
"datatype": "json"
},
"columns": [
{
data: null,
title: "<input type=\"checkbox\" id=\"btnSelAllStudents\">",
render: function (data, type, row, meta) {
return '<input type="checkbox" id="cbxRegStudent_' + row.ID + '" value="' + row.ID + '">';
},
targets: "no-sort",
orderable: false
},
{ data: "ID", title: "ID" },
{ data: "FullName", title: "#Resource.FullName" },
{ data: "Email", title: "#Resource.Email" },
{ data: "BirthDate", title: "#Resource.BirthDate" },
{
data: null, title: "Actions",
render: function (data, type, row, meta) {
/*return '<input type="button" class="btn-print printrec" id="' + row.ID + '" value="Print"/>';*/
return '#Resource.Profile | #Resource.Edit';
},
targets: "no-sort",
orderable: false
}
],
order: [],
});
$("#btnSelAllStudents").on("change", function (e) {
$("input[id^='cbxRegStudent_']").prop("checked", $(this).prop("checked"));
});
$('#registrationTable').on('processing.dt', function (e, settings, processing) {
$("#btnSelAllStudents").prop("checked", false);
}).dataTable();
});

MVC 3 asp.net 500 internal server error

hi guys sorry i m really new to mvc3 javascript jquery etc.
i have an internal server error 500
this is the controller:
[HttpGet]
public JsonResult GetEmail(string title, string notes)
{
byte[] pdf = null;
byte[] excel = null;
string userEmail = "";
try
{
pdf = GetFileForMail("PDF", "ServiceArea_" + System.DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".pdf", title, notes);
excel = GetFileForMail("EXCEL", "ServiceArea_" + System.DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".xls", title, notes);
MembershipUser mu = Membership.GetUser(this.MembershipData.Principal.Identity.Name);
userEmail = mu.Email.ToString();
System.Net.Mail.MailMessage mailMsg = new System.Net.Mail.MailMessage(userEmail,
"mailexample#mail.com",
title,
notes);
mailMsg.To.Add("no-replay#valuelab.it");
mailMsg.IsBodyHtml = true;
string mese = "";
string giorno = "";
string ore = "";
if (DateTime.Now.Month < 10)
mese = "0" + DateTime.Now.Month;
else
mese = "" + DateTime.Now.Month;
if (DateTime.Now.Day < 10)
giorno = "0" + DateTime.Now.Day;
else
giorno = "" + DateTime.Now.Day;
if(DateTime.Now.Hour < 10)
ore = "0" + DateTime.Now.Hour;
else
ore = "" + DateTime.Now.Hour;
System.Net.Mail.Attachment att = new System.Net.Mail.Attachment(new MemoryStream(pdf), DateTime.Now.Year + mese + giorno + "_" + ore + DateTime.Now.Minute + " Report.pdf", System.Net.Mime.MediaTypeNames.Application.Pdf);
System.Net.Mail.Attachment att2 = new System.Net.Mail.Attachment(new MemoryStream(excel), DateTime.Now.Year + mese + giorno + "_" + ore + DateTime.Now.Minute + " Report.xls", "application/vnd.ms-excel");
mailMsg.Attachments.Add(att);
mailMsg.Attachments.Add(att2);
System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient();
sc.Host = "192.168.99.1";
sc.Send(mailMsg);
return Json(new { text = "Everything is fine " + userEmail, risultato = true });
}
catch (Exception e) {
return Json(new { text = "Unexpected error" + userEmail , risultato = false});
}
}
and this is the way in which i call the controller:
jQuery.ajax({
type: "GET",
url: options.EmailUrl,
dataType: "json",
data:
{
title: viewModel.saReportTitle(),
notes: viewModel.saReportNotes()
},
success: function (data, textStatus, jqXHR) {
jQuery("#sa-dialog-alert").dialog('open');
jQuery("#sa-dialog-alert").dialog('option', 'title', 'Invio Mail Eseguito');
jQuery("#sa-dialog-alert").text(data.text);
}
,
error: function (data, textStatus, errorThrown) {
jQuery("#sa-dialog-alert").dialog('open');
jQuery("#sa-dialog-alert").dialog('option', 'title', 'Errore');
jQuery("#sa-dialog-alert").text("Errore nell'invio mail: " + errorThrown);
}
});
If you read the code the controller just send an email
and IT WORK FINE THERE are no exception
so why ajax say there is a 500 internal server error?
By default GET requests are not allowed on JsonResult so you need to excplicitly allow them, with setting the JsonRequestBehavior property:
return Json(
new { text = "Everything is fine " + userEmail, risultato = true },
JsonRequestBehavior.AllowGet
);
Or use POST as your request method in your AJAX call.

Scroll Events in TouchGridPanel

I am building a mobile application using Sencha Touch 1.0. I need to display report, for that am using grid given by Ext.ux.TouchGridPanel.
It is working fine.
Where as I need to capture Scroll event in Ext.ux.TouchGridPanel.
I have added 'scroll' in bubble event of Dataview.
I am also trying to capture the event after the Dataview created.
But nothing seems to be working. Below is the code which I have changed.
Does anybody has any idea how to capture the start of scroll event?
Thanks in advance.
Ext.ux.TouchGridPanel = Ext.extend(Ext.Panel, {
layout: "fit",
multiSelect: false,
initComponent: function () {
var me = this;
me.items = me.dataview = me.buildDataView();
Ext.ux.TouchGridPanel.superclass.initComponent.call(me);
var store = me.store;
store.on("update", me.dispatchDataChanged, me);
var dataview = me.dataview;
dataview.on('scroll', me.startScroll);
},
dispatchDataChanged: function (store, rec, operation) {
var me = this;
me.fireEvent("storeupdate", store, rec, operation);
},
startScroll: function (scroller, offset) {
console.log('is this event captured???')
var me = this;
me.fireEvent("scroll", this.scroller, offset);
},
buildDataView: function () {
var me = this, colModel = me.colModel, colNum = me.getColNum(false), cellWidth = 100 / colNum,
colTpl = '<div class="x-grid-head">';
colTpl += '<thead><tr class="x-grid-header">';
for (var i = 0; i < colModel.length; i++) {
var col = colModel[i];
var width = (Ext.isDefined(col.width)) ? ("width =" + (col.width - 4) + "%") : '';
colTpl += '<th class="x-grid-cell" ' + width + ' style="' + col.style + '" >' + col.header + '</th>';
}
colTpl += '</tr></thead>';
colTpl += '<tbody ><tpl for="."><tr class="x-grid-row">';
for (var i = 0; i < colModel.length; i++) {
var col = colModel[i];
var width = (Ext.isDefined(col.width)) ? ("width =" + col.width + "%") : '';
colTpl += '<td class="x-grid-cell" style="' + col.style + '" >{' + col.mapping + '}</td>';
}
colTpl += '</tr></tpl></tbody>';
colTpl += '</table></div>'
return new Ext.DataView({
store: me.store,
itemSelector: "tr.x-grid-row",
simpleSelect: me.multiSelect,
scroll: me.scroll,
tpl: new Ext.XTemplate(colTpl,
{
isRowDirty: function (dirty, data) {
return dirty ? "x-grid-row-dirty" : "";
}
}
),
prepareData: function (data, index, record) {
var column,
i = 0,
ln = colModel.length;
var prepare_data = {};
prepare_data.dirtyFields = {};
for (; i < ln; i++) {
column = colModel[i];
if (typeof column.renderer === "function") {
prepare_data[column.mapping] = column.renderer.apply(me, [data[column.mapping], column, record, index]);
} else {
prepare_data[column.mapping] = data[column.mapping];
}
}
prepare_data.isDirty = record.dirty;
prepare_data.rowIndex = index;
return prepare_data;
},
bubbleEvents: [
"beforeselect",
"containertap",
"itemdoubletap",
"itemswipe",
"itemtap",
"selectionchange",
"scroll"
]
});
},
// #private
onScrollStart: function () {
console.log("Are you coming here");
var offset = this.scroller.getOffset();
this.closest = this.getClosestGroups(offset);
this.setActiveGroup(this.closest.current);
},
// #private
onScroll: function (scroller, pos, options) {
}
});
Ext.reg("touchgridpanel", Ext.ux.TouchGridPanel);
We can directly access dataview scroller and check event of the same.
For eg.
newGrid = new Ext.ux.TouchGridPanel({....
after creation of the Panel just access its dataview scroller
newGrid.dataview.scroller.on('scroll', scrollGrid1);
var scrollGrid1 = function(scroller, offsets){
console.log(' Grid scrolling with offset ' + offsets.x + ' & ' + offsets.y);
}

Twitter and jQuery , render tweeted links

I am using jquery ajax to pull from the twitter api, i'm sure there's a easy way, but I can't find it on how to get the "tweet" to render any links that were tweeted to appear as a link. Right now it's only text.
$.ajax({
type : 'GET',
dataType : 'jsonp',
url : 'http://search.twitter.com/search.json?q=nettuts&rpp=2',
success : function(tweets) {
var twitter = $.map(tweets.results, function(obj, index) {
return {
username : obj.from_user,
tweet : obj.text,
imgSource : obj.profile_image_url,
geo : obj.geo
};
});
UPDATE:
The following function (plugin) works perfectly.
(function($) {
$.socialFader = function(options) {
var settings = {
tweetHolder : null,
tweetCount : 100,
fadeSpeed : 500,
tweetName: 'jquery'
};
if (options) {
$.extend(settings, options);
};
var URL = "http://search.twitter.com/search.json?q="+settings.tweetName+"&rpp=" + settings.tweetCount + "&callback=?";
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
delta = delta + (relative_to.getTimezoneOffset() * 60);
var r = '';
if (delta < 60) {
r = 'a minute ago';
} else if(delta < 120) {
r = 'couple of minutes ago';
} else if(delta < (45*60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (90*60)) {
r = 'an hour ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else {
r = (parseInt(delta / 86400)).toString() + ' days ago';
}
return r;
};
String.prototype.hashify = function() {
return this.replace(/#([A-Za-z0-9\/\.]*)/g, function(m) {
return '<a target="_new" href="http://twitter.com/search?q=' + m.replace('#','') + '">' + m + "</a>";
});
};
String.prototype.linkify = function(){
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
String.prototype.atify = function() {
return this.replace(/#[\w]+/g, function(m) {
return '' + m + "";
});
};
$.getJSON(URL, function(JSON) {
$.each(JSON.results, function(i, tweet) {
var profilePicture = tweet.profile_image_url;
var userLink = tweet.from_user;
var text = tweet.text;
text = text.linkify().atify().hashify();
var createdAt = new Date(tweet.created_at);
var myTweet = '' + userLink + ' ';
myTweet += text;
$(settings.tweetHolder).append('<li class="cycles">' + myTweet + '</li>');
});
var elements = $(settings.tweetHolder).children();
var timeOutStart = 5000;
function fader(elementId) {
setTimeout(function() {
$(elements[elementId]).fadeOut(settings.fadeSpeed, function() {
$(elements[elementId + 1]).fadeIn(settings.fadeSpeed);
});
}, timeOutStart * (elementId));
};
for (var j = 0; j < elements.length; j++) {
fader(j);
};
});
};
})(jQuery);
Within my Ready Statement :
$.socialFader({ tweetHolder:"#twitter", tweetName:"nettuts", tweetCount:2 });
Here is a plugin I wrote which really simplifies the tweet/json aggregation then parsing. It fades the tweets in and out. Just grab the needed code. Enjoy.
(function($) {
$.socialFader = function(options) {
var settings = {
tweetHolder : null,
tweetCount : 99,
fadeSpeed : 500,
};
if (options) {
$.extend(settings, options);
};
var URL = "http://search.twitter.com/search.json?q=jquery&rpp=" + settings.tweetCount + "&callback=?";
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
delta = delta + (relative_to.getTimezoneOffset() * 60);
var r = '';
if (delta < 60) {
r = 'a minute ago';
} else if(delta < 120) {
r = 'couple of minutes ago';
} else if(delta < (45*60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (90*60)) {
r = 'an hour ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else {
r = (parseInt(delta / 86400)).toString() + ' days ago';
}
return r;
};
String.prototype.hashify = function() {
return this.replace(/#([A-Za-z0-9\/\.]*)/g, function(m) {
return '<a target="_new" href="http://twitter.com/search?q=' + m.replace('#','') + '">' + m + "</a>";
});
};
String.prototype.linkify = function(){
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
String.prototype.atify = function() {
return this.replace(/#[\w]+/g, function(m) {
return '' + m + "";
});
};
$.getJSON(URL, function(JSON) {
$.each(JSON.results, function(i, tweet) {
var profilePicture = tweet.profile_image_url;
var userLink = tweet.from_user;
var text = tweet.text;
text = text.linkify().atify().hashify();
var createdAt = new Date(tweet.created_at);
var myTweet = '' + userLink + ' ';
myTweet += text;
$(settings.tweetHolder).append('<li class="cycles">' + myTweet + '</li>');
});
var elements = $(settings.tweetHolder).children();
var timeOutStart = 5000;
function fader(elementId) {
setTimeout(function() {
$(elements[elementId]).fadeOut(settings.fadeSpeed, function() {
$(elements[elementId + 1]).fadeIn(settings.fadeSpeed);
});
}, timeOutStart * (elementId));
};
for (var j = 0; j < elements.length; j++) {
fader(j);
};
});
};
})(jQuery);
You need to parse the tweet content, find the urls and then put them in between yourself.
Unfortunately, at the moment, the search API doesn't have the facility to break out tweet entities (i.e., links, mentions, hashtags) like some of the REST API methods. So, you could either parse out the entities yourself (I use regular expressions) or call back into the rest API to get the entities.
If you decide to call back into the REST API, and once you have extracted the status ID from the search API results, you would make a call to statuses/show like the following:
http://api.twitter.com/1/statuses/show/60183527282577408.json?include_entities=true
In the resultant JSON, notice the entities object.
"entities":{"urls":[{"expanded_url":null,"indices":[68,88],"url":"http:\/\/bit.ly\/gWZmaJ"}],"user_mentions":[],"hashtags":[{"text":"wordpress","indices":[89,99]}]}
You can use the above to locate the specific entities in the tweet (which occur between the string positions denoted by the indices property) and transform them appropriately.
If you prefer to parse the entities yourself, here are the (.NET Framework) regular expressions I use:
Link Match Pattern
(?:<\w+.*?>|[^=!:'"/]|^)((?:https?://|www\.)[-\w]+(?:\.[-\w]+)*(?::\d+)?(?:/(?:(?:[~\w\+%-]|(?:[,.;#:][^\s$]))+)?)*(?:\?[\w\+%&=.;:-]+)?(?:\#[\w\-\.]*)?)(?:\p{P}|\s|<|$)
Mention Match Pattern
\B#([\w\d_]+)
Hashtag Match Pattern
(?:(?:^#|[\s\(\[]#(?!\d\s))(\w+(?:[_\-\.\+\/]\w+)*)+)
Twitter also provides an open source library that helps capture Twitter-specific entities like links, mentions and hashtags. This java file contains the code defining the regular expressions that Twitter uses, and this yml file contains test strings and expected outcomes of many unit tests that exercise the regular expressions in the Twitter library.
How you process the tweet is up to you, however I process a copy of the original tweet, and pull all the links first, replacing them in the copy with spaces (so as not to modify the string length.) I capture the start and end locations of the match in the string, along with the matched content. I then pull mentions, then hashtags -- again replacing them in the tweet copy with spaces.
This approach ensures that I don't find false positives for mentions and hashtags in any links in the tweet.
I slightly modified previous one. Nothing lefts after all tweets disappears one by one.
Now it checks if there is any visible tweets and then refreshes tweets.
(function($) {
$.socialFader = function(options) {
var settings = {
tweetHolder : null,
tweetCount : 99,
fadeSpeed : 500,
};
if (options) {
$.extend(settings, options);
};
var URL = "http://search.twitter.com/search.json?q=istanbul&rpp=" + settings.tweetCount + "&callback=?";
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
delta = delta + (relative_to.getTimezoneOffset() * 60);
var r = '';
if (delta < 60) {
r = 'a minute ago';
} else if(delta < 120) {
r = 'couple of minutes ago';
} else if(delta < (45*60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (90*60)) {
r = 'an hour ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else {
r = (parseInt(delta / 86400)).toString() + ' days ago';
}
return r;
};
String.prototype.hashify = function() {
return this.replace(/#([A-Za-z0-9\/\.]*)/g, function(m) {
return '<a target="_new" href="http://twitter.com/search?q=' + m.replace('#','') + '">' + m + "</a>";
});
};
String.prototype.linkify = function(){
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
String.prototype.atify = function() {
return this.replace(/#[\w]+/g, function(m) {
return '' + m + "";
});
};
$.getJSON(URL, function(JSON) {
$(settings.tweetHolder).find('li.cycles').remove();
$.each(JSON.results, function(i, tweet) {
var profilePicture = tweet.profile_image_url;
var userLink = tweet.from_user;
var text = tweet.text;
text = text.linkify().atify().hashify();
var createdAt = new Date(tweet.created_at);
var myTweet = '' + userLink + ' ';
myTweet += text;
$(settings.tweetHolder).append('<li class="cycles">' + myTweet + '</li>');
});
var elements = $(settings.tweetHolder).children();
var timeOutStart = 5000;
function fader(elementId) {
setTimeout(function() {
$(elements[elementId]).fadeOut(settings.fadeSpeed, function() {
$(elements[elementId + 1]).fadeIn(settings.fadeSpeed);
});
if (jQuery('#twitter ul li.cycles:visible').length==1) {
jQuery.socialFader({ tweetHolder:"#twitter ul", tweetCount:5 });
}
}, timeOutStart * (elementId));
};
for (var j = 0; j < elements.length; j++) {
fader(j);
};
});
};
})(jQuery);
jQuery(document).ready(function(){
jQuery.socialFader({ tweetHolder:"#twitter ul", tweetCount:5 });
});

Resources