parameter complex object is coming into JavaScript function as undefined - c#

On Page 1 I get the object I need:
ProjectSearchCriteria = (GBLProjectSearchCriteria)Session[GblConstants.SESSION_PROJECT_SEARCH_CRITERIA];
I'm trying to pass this to an API on a page load of Page 2.
Page 2:
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<link href="../x.css" type="text/css" rel="stylesheet">
<link href="../Content/kendo.common.min.css" rel="stylesheet" />
<link href="../Content/kendo.default.min.css" rel="stylesheet" />
</head>
<body>
<form id="frmProjectSearchResults" runat="server">
</form>
<script src="../Scripts/ProjectsTreeView.js"> </script>
<script type="text/javascript">
CreateProjectTree(<%= ProjectSearchCriteria %>);
</script>
</body>
</html>
And this is the JavaScript function:
function CreateProjectTree(searchCriteria)
{
debugger;
var projects = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: "../api/projects?searchcriteria =" + searchCriteria,
contentType: "application/json"
},
parameterMap: function (data, operation) {
return JSON.stringify(data);
}
},
schema: {
model: {
children: "seasons"
}
}
});
$("#treeview").kendoTreeView({
dataSource: projects,
loadOnDemand: true,
dataUrlField: "LinksTo",
checkboxes: {
checkChildren: true
},
dataTextField: ["Title"],
select: treeviewSelect
});
function treeviewSelect(e) {
var node = this.dataItem(e.node);
window.open(node.NotificationLink, "_self");
}
}
Can anyone help me understand what I'm doing wrong?

Maybe this:
<script type="text/javascript">
CreateProjectTree("\"" + <%= ProjectSearchCriteria %> + "\"");
</script>

Related

Failed to load resource: Uncaught TypeError: $(...).select2 is not a function

So my MVC application keeps on throwing an Http internal server error with status code 500 when it renders my view.
The error it is throwing is a JQuery "Uncaught TypeError: $(...).select2 is not a function"
Uncaught TypeError: $(...).select2 is not a function
at HTMLDocument.<anonymous> (AddUser:381)
at fire (jquery-1.11.0.js:3100)
at Object.fireWith [as resolveWith] (jquery-1.11.0.js:3212)
at Function.ready (jquery-1.11.0.js:3424)
at HTMLDocument.completed (jquery-1.11.0.js:3454)
Using debugger tools, it throws the error here:
$('selectUser').select2();
This is how I call my script:
#section Scripts {
<script type="text/javascript" src="#Url.Content("~/Content/Template/js/plugins/jquery-ui-1.8.16.custom.min.js")"></script>
#Scripts.Render("~/bundles/forms")
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/css/select2.min.css" rel="stylesheet" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/js/select2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('selectUser').select2();
});
</script>
Some SO posts suggest that this error is caused when you omit type="text/javascript"in your script tag or when you call the select2 function before the reference to the CDN service but as it clearly shows on my code all seems fine regarding the aforementioned.
According to this Uncaught TypeError: $(...).select2 is not a function, I am told to make sure if I have one version of JQuery loaded and all seems fine
Here is some additional code from my View that will help in reproducing the problem:
<script>
function submitForm() {
var usersRoles = new Array;
jQuery("#dualSelectRoles2 option").each(function () {
usersRoles.push(jQuery(this).val());
});
var model = new Object();
model.userId = jQuery('#selectUser').val();
model.rolesList = usersRoles;
console.log('model: ' + 'user: ' + model.userId + 'roles: ' + model.rolesList);
console.log('JSON: ' + JSON.stringify(model));
jQuery('#loading3').show();
jQuery.ajax({
type: "POST",
url: "#Url.Action("AddUser")",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(model),
success: function (data) { showSuccessMessage(data); },
failure: function (errMsg) {
jQuery('#loading3').hide();
alert(errMsg);
}
});
return false;
}
//Shows the success message
function showSuccessMessage(data) {
jQuery('#loading3').hide();
alert(data);
}
</script>
Controller:
public ActionResult AddUser()
{
if (TempData["StatusMessage"] != null)
{
ViewBag.StatusMessage = TempData["StatusMessage"].ToString();
}
else
{
ViewBag.StatusMessage = "";
}
AddUserToRolesViewModel vm = new AddUserToRolesViewModel();
vm.Users = db.Users.ToList();
return View(vm);
}
EDIT:
Just to make sure that JQuery Core didn't load twice (once in Master and once in Content page) - I have included the markup for my master page.
_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="shortcut icon" href="/favicon.ico" />
#Styles.Render("~/Content/Template/css/style.css")
<!--[if IE 9]>
<link rel="stylesheet" media="screen" href="#Url.Content("~/Content/Template/css/ie9.css")"/>
<![endif]-->
<!--[if IE 8]>
<link rel="stylesheet" media="screen" href="#Url.Content("~/Content/Template/css/ie8.css")"/>
<![endif]-->
<!--[if IE 7]>
<link rel="stylesheet" media="screen" href="#Url.Content("~/Content/Template/css/ie7.css")"/>
<![endif]-->
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript" src="#Url.Content("~/Content/Template/js/custom/general.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Content/Template/js/plugins/ui.spinner.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Content/Template/js/plugins/jquery.jgrowl.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Content/Template/js/plugins/jquery.alerts.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Content/Template/js/custom/elements.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Content/Template/js/plugins/colorpicker.js")"></script>
<!--[if lt IE 9]>
<script src="http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"></script>
<![endif]-->
<!--[if lte IE 8]><script language="javascript" type="text/javascript" src="#Url.Content("~/Content/Template/js/plugins/excanvas.min.js")"></script><![endif]-->
<title>#ViewBag.Title</title>
</head>
<body class="loggedin">
#Html.Partial("_Header_top")
<!-- START OF MAIN CONTENT -->
<div class="mainwrapper">
<div class="mainwrapperinner">
#Html.Partial("_Menu_left")
<div class="maincontent">
<div class="maincontentinner">
#RenderBody()
</div>
<div class="footer">
#Html.Partial("_Footer")
</div>
</div>
</div>
</div><!--mainwrapper-->
<!-- END OF MAIN CONTENT -->
</body>
#RenderSection("scripts", required: false)
#Scripts.Render("~/bundles/jqueryval")
</html>
Update II:
So I went ahead to my App_Start folder and navigated to my BundleConfig.cs and there I noticed something:
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js",
"~/Content/Template/js/plugins/jquery-ui-
1.8.16.custom.min.js"
}
According to this link: Usage of the ASP.NET MVC4 jquery/javascript bundles and I realized that file "~/Content/Template/js/plugins/jquery-ui-1.8.16.custom.min.js" had alreasdy been added to this bundle and referenced in my content page (AddUser.cshtml) as:
<script type="text/javascript" src="#Url.Content("~/Content/Template/js/plugins/jquery-ui-1.8.16.custom.min.js")"></script>
At this point, I strongly believed this was going to fix the problem and so I removed this reference in my content page because I believed that that could be loading JQuery core twice but still nothing. The error still persists. What else can I do to try solve this?
Worthy mention that this error persists across all browsers (Chrome, IE & Firefox)

Rendering fullcalendar to pdf using wkhtmltopdf allways omit Days

I'm currenty using Wkhtmltopdf to export Full Calendar to PDF.
My Html code is (only Body) :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fine & Country</title>
<link href="https://fonts.googleapis.com/css?family=Fenix:400" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Dosis:400,600" rel="stylesheet">
<link href="http://localhost:21792/Content/select2.min.css" rel="stylesheet" />
<link href="http://localhost:21792/Content/fullcalendar_year.css" rel="stylesheet" />
<link href="http://localhost:21792/Content/jquery-ui.css" rel="stylesheet" />
<link href="http://localhost:21792/Content/select2.min.css" rel="stylesheet" />
<style>
.fc-left, .fc-right
{
display: none;
}
</style>
</head>
<body>
<div id="calendar-full"></div>
<script src="http://localhost:21792/Scripts/jquery-1.10.2.js"></script>
<script src="http://localhost:21792/Scripts/moment.min.js"></script>
<script src="http://localhost:21792/Scripts/fullcalendar_year.js"></script>
<script src="http://localhost:21792/Scripts/Custom/pt.js"></script>
<script src="http://localhost:21792/Scripts/jquery-ui.min.js"></script>
<script src="http://localhost:21792/Scripts/Custom/HollidayPdf.js"></script>
<script type="text/javascript">
while (window.status != "READY");
</script>
</body>
</html>
I guarantee that json calls finish before load the page.
My Javascript code is (File: HollidayPdf.js):
var fullCalendarApproval;
var events, notWorkingDays;
var date = new Date();
var isLoadedNotWorkingDays = false, isLoadedEvents = false;
jQuery.ajax({
url: 'http://localhost:21792/Hollidays/LoadNotWorkingDays',
type: 'GET',
dataType: "json",
contentType: "application/javascript",
async: false,
cache: false,
success: function (data) {
isLoadedNotWorkingDays = true;
notWorkingDays = data;
}
});
jQuery.ajax({
url: 'http://localhost:21792/Hollidays/ListAllHolidaysSchedulled',
type: 'GET',
dataType: "json",
contentType: "application/javascript",
async: false,
cache: false,
success: function (data) {
isLoadedEvents = true;
events = data;
}
});
while (!isLoadedNotWorkingDays && !isLoadedEvents);
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
if (jQuery('#calendar-full').length > 0) {
jQuery('#calendar-full').fullCalendar({
defaultView: 'year',
header: {
left: 'prev,next today',
center: 'title',
right: 'year,month'
},
yearColumns: 2,
firstDay: 1,
editable: false,
events: events,
loading: function (bool) {
},
viewRender: function (view, element) {
jQuery.each(notWorkingDays, function (i) {
jQuery('.fc-day[data-date="' + notWorkingDays[i]["date"] + '"]').css('background', "#e2dec1");
});
}
});
}
window.status = "READY";
But every time i execute wkhtmltopdf with the following line i get only Weeks.
My command line is :
wkhtmltopdf.exe --window-status READY D:\Projects\CRM\FineCountry.html D:\Projects\CRM\test1.pdf
For what i've seen only transform part of the calendar, it's weird.
Does anyone faced similar Issue???

how to send xml parameter to WCF?

How to send xml parameter to call WCF method? My client side code is in AJAX,JSON using jQuery.I want to pass xml value as parameter.How to pass xml value?
My xml value is
<value><Root>mydata</Root></value>
My client side code--
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.min.js"></script>
<script type="text/javascript" >
jQuery.support.cors = true;
var bhRequest = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<s:Body>" +
"<GetSMC xmlns=\"http://tempuri.org/\">" +
"<value><Root>MyValue</Root></value>" +
"</GetSMC>" +
"</s:Body>" +
"</s:Envelope>";
$(document).ready(function () {
$("#btnWCFBasicHttp").click(function () {
alert("hi");
$.ajax({
type: "POST",
url: "http://localhost:8130/MyService.svc/bh/",
data: bhRequest,
timeout: 10000,
contentType: "text/xml",
dataType: "xml",
beforeSend: function (xhr) {
xhr.setRequestHeader("SOAPAction", "http://tempuri.org/IMyService/GetSMC");
},
success: function (data) {
alert("success");
$(data).find("GetSMCResponse").each(function () {
document.getElementById('Label2').innerHTML = $(this).find("GetSMCResult").text();
});
},
error: function (xhr, status, error) {
alert(error);
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="btnWCFREST" type="button" value="Call WCF using JQuery" />
<label ID="Label1" runat="server" Text="Label"></label>
</div>
</form>
</body>
</html>
I'm not sure if it'll work, but try to put that XML inside
<![CDATA[ and ]]>
There is also some hack with string tag, but I don't know if it is necessary (maybe only CDATA tag will be enough):
WCF RESTFul service - Pass XML as string to service
you will encrypt by base64 and pass it,on the server client you can decrypt

Fineuploader and MVC4

I try to implement Fineuploader in my MVC4 project but it always fails to upload. What i did:
added css and js files to my view:
<link href="~/Content/fineuploader.css" rel="stylesheet" />
<script src="~/Scripts/js/util.js"></script>
<script src="~/Scripts/js/button.js"></script>
<script src="~/Scripts/js/dnd.js"></script>
<script src="~/Scripts/js/handler.base.js"></script>
<script src="~/Scripts/js/handler.form.js"></script>
<script src="~/Scripts/js/handler.xhr.js"></script>
<script src="~/Scripts/js/header.js"></script>
<script src="~/Scripts/js/jquery-plugin.js"></script>
<script src="~/Scripts/js/uploader.basic.js"></script>
<script src="~/Scripts/js/uploader.js"></script>
added the code for the upload button and exceution of the script (i think this isn't right?)
<script>
function createUploader() {
var uploader = new qq.FineUploader({
element: document.getElementById('fine-uploader'),
debug: true,
request: {
endpoint: '/Upload/UploadFile/'
}
});
}
window.onload = createUploader;
</script>
added the C# files to my project FineUpload.cs, FineUploadResult.cs and the Controller UploadController.cs. I also added a route to the controller:
routes.MapRoute(
name: "upload",
url: "Upload/UploadFile",
defaults: new { controller = "Upload", action = "UploadFile" }
);
The controller is:
public class UploadController : Controller
{
[HttpPost]
public FineUploaderResult UploadFile(FineUpload upload, string extraParam1, int extraParam2)
{
...
}
}
But UploadFile is never called on the server.
You seem to have messed up your script inclusions (order and everything). You should choose whether you need to use the FineUploaderBasic mode, the FineUploader mode or the jQuery plug-in mode. Given your code you seem to be using the standard mode.
Here's a full working example and the minimal markup:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<link href="~/Content/fineuploader.css" rel="stylesheet" />
</head>
<body>
<div id="fine-uploader">Click me to upload a file</div>
<script src="~/Scripts/js/header.js"></script>
<script src="~/Scripts/js/util.js"></script>
<script src="~/Scripts/js/button.js"></script>
<script src="~/Scripts/js/handler.base.js"></script>
<script src="~/Scripts/js/handler.form.js"></script>
<script src="~/Scripts/js/handler.xhr.js"></script>
<script src="~/Scripts/js/uploader.basic.js"></script>
<script src="~/Scripts/js/dnd.js"></script>
<script src="~/Scripts/js/uploader.js"></script>
<script type="text/javascript">
function createUploader() {
var uploader = new qq.FineUploader({
element: document.getElementById('fine-uploader'),
debug: true,
request: {
endpoint: '#Url.Action("UploadFile", "Uploader")'
}
});
}
createUploader();
</script>
</body>
</html>
Also your controller action seem to be taking some extra integer parameter. If you do not specify it with the request, this request will obviously fail. Use a nullable integer in this case.

How to set a custom Jquery auto complete response message

I am using Jquery auto complete text box , in that i am entering a name starts with z or something which is not available in the database, at that time I need to display a custom message in auto complete mentioning that "No Datas Found"
I came up with a solution,please Correct me if the below mentioned solution is incorrect or any other alternate way to achieve it.
Thanks in advance.
AutoComplete TextBox.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="AutoCompleteTextBox.aspx.cs" Inherits="Ajax_Using_Jquery.AutoCompleteTextBox" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Ajax Auto Complete Using Jquery</title>
<script type="text/javascript" src="JQuery/jquery-1.9.0.mini.js"></script>
<script type="text/javascript" src="JQuery/jquery-ui.min.js" ></script>
<%--<link type="text/css" href="StyleSheet/jquery-ui.css" rel="Stylesheet" />--%>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<%--<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script> --%>
<script type="text/javascript">
$(document).ready(function () {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "AutoCompleteFetchService.asmx/getUserNames",
data: "{'TextBoxVal':'" + document.getElementById('txtName1').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
if (data.d == "" || data.d == null || typeof (data.d) == 'undefined') {
response(["no search found"]);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error " + XMLHttpRequest);
alert("error " + textStatus);
alert("error " + errorThrown);
}
});
}
});
});
</script>
<%-- <link href="StyleSheet/jquery-ui.css" type="text/css" rel="Stylesheet" />--%>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>
<div>
User Name :
<input type="text" id="txtName1" class="autosuggest" />
</div>
</td>
</tr>
</table>
</form>
</body>
</html>
AutoCompleteFetchService.asmx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;
namespace Ajax_Using_Jquery
{
/// <summary>
/// Summary description for AutoCompleteFetchService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService()]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class AutoCompleteFetchService : System.Web.Services.WebService
{
[WebMethod]
public List<string> getUserNames(string TextBoxVal)
{
string strCon;
List<string> objList = new List<string>();
strCon = ConfigurationManager.ConnectionStrings["EmpNameFetch"].ConnectionString;
SqlConnection con = new SqlConnection(strCon);
SqlCommand cmd = new SqlCommand(#"select EmpName from newTb2 where EmpName like '%" + TextBoxVal + "%'", con);
con.Open();
SqlDataReader objReader = cmd.ExecuteReader();
while (objReader.Read())
{
objList.Add(objReader["EmpName"].ToString());
}
con.Close();
return objList;
}
}
}
The following prints "0 results" if no results are found and, if results are found, prints a helpful message to the user that says "Click or Arrow Up/Down"
messages: {noResults: '0 Results',results: function() {return 'Click or Arrow U/D'; } }

Categories