MVC 3 asp.net 500 internal server error - asp.net-mvc-3

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.

Related

Why is variable is showing as a string?

I don't understand why call_script_id is showing as a string instead of the content stored in the variable. The other variables work fine, but literally, call_script_id is setting id="call_script_id" whereas call_reason_id is setting the proper number.
$.ajax({
url: "../selections/call-reasons.php",
type: 'post',
data: {company_uid:"<?php echo $row['company_uid']; ?>"},
dataType: 'json',
success:function(response){
var len = response.length;
$("#call_reasons").empty();
for( var i = 0; i<len; i++){
var call_script_id = response[i]['call_script_id'];
var call_reason_id = response[i]['call_reason_id'];
var call_type = response[i]['call_type'];
var active = response[i]['active'];
$("#call_reasons").append("<tr><td href='../modals/call-types.php' class='call_reason_row' id=" + call_script_id + ">" + call_reason_id + "</td><td id=" + call_script_id + "></td><td id=" + call_script_id + "></td><td><i class='far fa-edit'></i><i class='far fa-calendar-alt'></i><i class='far fa-trash-alt call_reason_trash' id=" + call_reason_id + "></i></td></tr>");
}
// Brings up the pop up to edit call reasons/types
$(".call_reason_row").click(function() {
$('#main-content',parent.document).load($(this).attr('href'), {call_reason_id: this.id, company_uid: "<?php echo $row["company_uid"];?>", active: active});
});
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
$sql = "SELECT cs.id, cs.call_reason, sct.call_type FROM call_script AS cs INNER JOIN selection_call_types AS sct ON cs.call_reason = sct.id WHERE cs.company_uid = '$company_uid'";
$result = mysqli_query($conn, $sql);
$my_array = array();
while($row = mysqli_fetch_array($result) ){
$call_script_id = $row['id'];
$call_reason_id = $row['call_reason'];
$call_type = $row['call_type'];
$active = $row['active'];
$my_array[] = array("call_script_id" => call_script_id, "call_reason_id" => $call_reason_id, "call_type_id" => $call_type, "active" => $active);
}
I guess I expecting the issue to be in ajax since I'm not as familiar with the language. Instead, it was because I was missing the dollar sign on the variable call_reason_id, in $my_array on the very last line.

How to Use Only One MVC Controller For Entire Application?

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>

can't get parameter from XMLHttpRequest

I can see parameters from js, but I can't use getParameter to get them. what's the problem?
js code
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var req = new XMLHttpRequest();
req.open("POST", "../PersonTest", true);
req.onreadystatechange = function(){
if (req.readyState == 4) {
if (req.status == 200) {
alert(req.responseText);
} else {
alert("HTTP error " + req.status + ": " + req.statusText);
}
}
}
req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
req.send("email=" + email + "&password=" + password);
servlet code
response.setContentType("text/xml;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
//print request content
ServletInputStream is = request.getInputStream();
...
System.out.println(new String(baos.toByteArray(), "utf-8"));
//get parameter
String email = request.getParameter("email");
String password = request.getParameter("password");
System.out.println(email + " " + password);
}
servlet output:
email=123&password=123
null null

Pass function parameters for json fill drop down

How would pass the parameter into "foodName" from the function that sends the url and id? i.e. could you do something like the function:
call('/url/to/foodlist', "foodList", "food");
and replace
var input = item.food;?
Below is working code but would like a more general function then having to use part of name in the function (replace foodName so that it isn't in this function)
function call(url, id){
var string = '';
$.ajax({
type: "GET",
url: url,
success: function (item)
if (item != '') {
var input = item.foodName;
for (var i = 0; i < input.length; i++) {
string += = '<option value=' + input[i].name + '">' + input[i].name + '</option>';
}
$('#' + id). append(string);
}
});
call('/url/to/foodlist', "foodList");
function call(url, id, paramName){
var string = '';
$.ajax({
type: "GET",
url: url,
success: function (item)
if (item != '') {
var input = item[paramName]; // you can access to the properties using braces
for (var i = 0; i < input.length; i++) {
string += = '<option value=' + input[i].name + '">' + input[i].name + '</option>';
}
$('#' + id). append(string);
}

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