ReferenceError:event is not defined - c#

In my asp.net mvc3 page, i am using jquery to show a calender to display the events added in the database. Its working fine in google chrome but its showing below error in firefox 19.0.2
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery-1.8.3.js")"> </script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-i.css">
<link rel="stylesheet" href="../../Content/css/styleui.css" />
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("/Page/dates", null, function (data) {
var s = eval(data);
alert(s);
showevents(s);
});
function showevents(events) {
$("#datepicker").datepicker({
beforeShowDay: function (date) {
var result = [true, '', null];
var matching = $.grep(events, function (event) {
return event.Date.valueOf() === date.valueOf();
});
if (matching.length) {
result = [true, 'highlight', event.Title];
}
return result;
},
onSelect: function (dateText) {
var date, selectedDate = new Date(dateText), i = 0, event = null;
while (i < events.length && !event) {
date = events[i].Date;
if (selectedDate.valueOf() === date.valueOf()) {
event = events[i];
}
i++;
}
if (event) {
//return [true, "Highlighted", event.Title];
alert(event.Title);
}
}
});
}
});
</script>
<div id="datepicker">
[16:35:16.336] ReferenceError: event is not defined # http://code.jquery.com/jquery-1.8.3.js:579

You are probably missing var event; at the start of showevents function. See comments:
beforeShowDay: function (date) {
var result = [true, '', null];
var matching = $.grep(events, function (event) {
return event.Date.valueOf() === date.valueOf();
});
if (matching.length) {
// event is not defined
result = [true, 'highlight', event.Title];
}
return result;
},
onSelect: function (dateText) {
var date, selectedDate = new Date(dateText), i = 0, event = null;
while (i < events.length && !event) {
date = events[i].Date;
if (selectedDate.valueOf() === date.valueOf()) {
// event is not defined
event = events[i];
}
i++;
}
if (event) {
//return [true, "Highlighted", event.Title];
// event is not defined
alert(event.Title);
}
}

Related

Cascading (Dependent) DropDownList using ASP.NET MVC

I have implemented Cascading (Dependent) DropDownList using ASP.NET MVC.
This is the tutorial
Now I need show alert message box after insert data and redirect on Index page in ASP.NET MVC.
To show alert message in ASP.NET MVC after insert data using store procedure from MySQL database, I have write the code like as shown below.
<script type="text/javascript">
$(function () {
var msg = '#ViewData["result"]';
if (msg > 0)
{
alert("User Details Inserted Successfully");
window.location.href = "#Url.Action("Index", "Home")";
}
});
</script>
The data is correctly registered in the database table and the alert message box after insert data it's show.
But the redirect to index.cshtml not working because all the DropDownList on the form are empty except the first DropDownList that populates correctly.
window.location.href = "#Url.Action("Index", "Home")";
I mean that all other (populated cascading) DropDownList are enabled but empty.
I need redirect to Index Action page and being able to reload a new record, with this redirection it is impossible because the populated cascading DropDownList remain empty... instead of disabled and populated from value of first dropdownlist...
How to do resolve this?
Thanks.
Update 2021-01-02
#section Scripts {
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/Scripts/DatePicker.js");
#Styles.Render("~/Content/cssjqryUi")
<script type="text/javascript">
$(function () {
var msg = '#ViewData["result"]';
console.log(msg);
if (msg > 0)
{
alert("User Details Inserted Successfully");
var url = "#Url.Action("Index", "Home")";
window.location.href = url;
}
});
</script>
<script src="Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
jQuery(function ($) {
$.validator.addMethod('date',
function (value, element) {
if (this.optional(element)) {
return true;
}
var ok = true;
try {
$.datepicker.parseDate('dd/mm/yy', value);
}
catch (err) {
ok = false;
}
return ok;
});
$("#thedate").datepicker(options);
$(function () {
$(".loading").hide();
$("select").each(function () {
if ($(this).find("option").length <= 1) {
$(this).attr("disabled", "disabled");
}
});
$("select").change(function () {
var value = 0;
if ($(this).val() != "") {
value = $(this).val();
}
var id = $(this).attr("id");
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: '{type: "' + id + '", value: "' + value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var dropDownId;
var list;
switch (id) {
case "CountryId":
list = response.States;
DisableDropDown("#TicketId");
DisableDropDown("#CityId");
dropDownId = "#TicketId";
list = response.Ticket;
PopulateDropDown("#TicketId", list);
break;
case "TicketId":
list = response.States;
DisableDropDown("#StateId");
PopulateDropDown("#StateId", list);
break;
case "StateId":
dropDownId = "#CityId";
list = response.Cities;
DisableDropDown("#CityId");
PopulateDropDown("#CityId", list);
dropDownId = "#CityId2";
list = response.Cities2;
PopulateDropDown("#CityId2", list);
$("#GPS").val(response.GPS);
break;
}
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
function DisableDropDown(dropDownId) {
$(dropDownId).attr("disabled", "disabled");
$(dropDownId).empty().append('<option selected="selected" value="">[ === Select === ]</option>');
}
function PopulateDropDown(dropDownId, list) {
var modal = $('<div />');
modal.addClass("modalBackground");
$('body').append(modal);
var loading = $(".loading");
loading.show();
var top = Math.max($(window).height() / 2 - loading[0].offsetHeight / 2, 0);
var left = Math.max($(window).width() / 2 - loading[0].offsetWidth / 2, 0);
loading.css({ top: top, left: left });
setTimeout(function () {
if (list != null && list.length > 0) {
$(dropDownId).removeAttr("disabled");
$.each(list, function () {
$(dropDownId).append($("<option></option>").val(this['Value']).html(this['Text']));
});
$(".loading").hide();
$('.modalBackground').remove();
}
}, 1000);
}
</script>
}
update controller
[HttpPost]
public ActionResult Index(PersonModel person)
{
MTsqlinsert(person); //Insert values in the database
if (ModelState.IsValid)
{
PersonModel personModel = new PersonModel();
person.Countries = PopulateDropDown("SELECT CountryId, CountryName FROM Countries", "CountryName", "CountryId");
person.States = PopulateDropDown("SELECT StateId, StateName FROM States WHERE CountryId = " + countryId, "StateName", "StateId");
person.Cities = PopulateDropDown("SELECT CityId, CityName FROM Cities WHERE StateId = " + stateId, "CityName", "CityID");
ViewData["result"] = "1";
return RedirectToAction("Index");
}
return View(person);
}
[HttpGet]
[OutputCache(NoStore = true, Duration = 60, VaryByParam = "*")]
public ActionResult Index()
{
PersonModel personModel = new PersonModel
{
Countries = PopulateDropDown("SELECT CountryId, CountryName FROM Countries", "CountryName", "CountryId");
};
return View(personModel);
}

Problems when closing save dialog box jeasyui grid

I'm facing a problem when doing
http://www.jeasyui.com/tutorial/app/crud/index.html
After I saved the new item, I've successfully update the database, but when the javascript calling saveUser function to close the dialog box and refresh the grid, I always got this error:
Uncaught SyntaxError: Unexpected token )
at HTMLFormElement.success (http://localhost:58137/scripts/scripteasyui.js:22:44)
at HTMLIFrameElement.cb (http://www.jeasyui.com/easyui/jquery.easyui.min.js:7707:14)
at HTMLIFrameElement.handle (http://code.jquery.com/jquery-1.6.min.js:16:32793)
at HTMLIFrameElement.k (http://code.jquery.com/jquery-1.6.min.js:16:29553)
I'm using MVC c#, here's my code:
For the head on the view html
<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/icon.css">
<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/color.css">
<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/demo/demo.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>
<script type="text/javascript" src="http://www.jeasyui.com/easyui/jquery.easyui.min.js"></script>
<script src="~/scripts/scripteasyui.js"></script>
for the scripteasyui.js file:
var url;
function newBrand() {
$('#dlg').dialog('open').dialog('center').dialog('setTitle', 'New User');
$('#fm').form('clear');
url = 'SaveBrands';
}
function editBrand() {
var row = $('#dg').datagrid('getSelected');
if (row) {
$('#dlg').dialog('open').dialog('center').dialog('setTitle', 'Edit User');
$('#fm').form('load', row);
url = 'update_user.php?id=' + row.id;
}
}
function saveBrand() {
$('#fm').form('submit', {
url: url,
onSubmit: function () {
return $(this).form('validate');
},
success: function (result) {
var result = eval('(' + result + ')');
if (result.errorMsg) {
$.messager.show({
title: 'Error',
msg: result.errorMsg
});
} else {
$('#dlg').dialog('close'); // close the dialog
$('#dg').datagrid('reload'); // reload the user data
}
}
});
}
function destroyBrand() {
var row = $('#dg').datagrid('getSelected');
if (row) {
$.messager.confirm('Confirm', 'Are you sure you want to destroy this user?', function (r) {
if (r) {
$.post('destroy_user.php', { id: row.id }, function (result) {
if (result.success) {
$('#dg').datagrid('reload'); // reload the user data
} else {
$.messager.show({ // show error message
title: 'Error',
msg: result.errorMsg
});
}
}, 'json');
}
});
}
}
for the save method on the controller
public void SaveBrands()
{
string brandid = Request.Form["brandid"];
string brandname = Request.Form["brandname"];
using (ItemsEntities db = new ItemsEntities())
{
db.Brands.Add(new Brand { BrandID = brandid, BrandName = brandname });
db.SaveChanges();
}
}
For showing the list data
public JsonResult ShowBrands(string sidx, string sort, int page, int rows)
{
sort = (sort == null) ? "" : sort;
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
using (ItemsEntities db = new ItemsEntities())
{
var brandqry = db.Brands.OrderBy(e => e.BrandID);
int RecCount = brandqry.Count();
var totalPages = (int)Math.Ceiling((float)RecCount / (float)rows);
var jsonData = new
{
total = totalPages,
page,
records = RecCount,
rows = brandqry.ToList(),
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
}
I found the answer I need to serialized the result into jason for the result parameter on javascript
string jsondata = JsonConvert.SerializeObject(brandmdl);
return Json(jsondata);

Jquery colorbox not working after gridview page change

I am having issue with Jquery colorbox with gridview paging.
When First time page is loaded colorbox is working fine but when I change gridview page through paging its not working.
Here is my javascript code
<script type="text/javascript">
$(document).ready(function () {
$(".example6").colorbox({
iframe: true, innerWidth: 425, innerHeight: 173, onClosed: function () {
($get('<%= btnInsertData_dummy.ClientID %>')).click();
}
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(EndRequestHandler);
});
function EndRequestHandler(sender, args) {
$(".example6").colorbox({
iframe: true, innerWidth: 425, innerHeight: 173, onClosed: function () {
var path = sender._postBackSettings.sourceElement.pathname;
var myArray = new Array();
myArray = path.split('/');
if (myArray[1].toString() != "Default.aspx") {
($get('<%= btnInsertData_dummy.ClientID %>')).click();
}
}
});
}
</script>
and in gridview I am binding hyperlink on Rowdatabound
if (e.RowType != GridViewRowType.Data) return;
var securrityKey = e.GetValue("str_securitykey");
System.Web.UI.WebControls.HyperLink grdHyper =
grid.FindRowCellTemplateControl(e.VisibleIndex, null, "grdhyper")
as System.Web.UI.WebControls.HyperLink;
if (securrityKey.ToString() != "")
{
grdHyper.Visible = false;
}
else
{
var number = e.GetValue("lng_rndnum");
var lngId = e.GetValue("lng_id");
grdHyper.CssClass = "example6 cboxElement";
grdHyper.NavigateUrl = "GenerateSecurityKey.aspx?number=" + number.ToString() + "&id=" + lngId.ToString();
}
and its not working after paging is clicked
Change your code from add_endRequest to add_pageLoaded in your jquery code. And remove your (document).ready(function(){ jquery code and placed your code of colorbox method inside add_pageLoaded method. Hope this might solve your issue.

Disable Jquery autocomplete dropdown from codebehind c#

I am using http://jqueryui.com/autocomplete/#combobox for my dropdownlist and it works well.
My problem here is when I disable the dropdown list from code behind it doesn't work.
My code is here.
ASPX
<asp:DropDownList runat="server" CssClass="Dropdown" ID="ddlStatus"> </asp:DropDownList>
JS
function pageLoad() {
/******** Auto Complete *********************/
$(function () {
$("#<%= ddlStatus.ClientID %>").combobox();
});
(function ($) {
$.widget("custom.combobox", {
_create: function () {
this.wrapper = $("<span>")
.addClass("custom-combobox")
.insertAfter(this.element);
this.element.hide();
this._createAutocomplete();
this._createShowAllButton();
},
_createAutocomplete: function () {
var selected = this.element.children(":selected"),
value = selected.val() ? selected.text() : "";
this.input = $("<input>")
.appendTo(this.wrapper)
.val(value)
.attr("title", "")
.addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
.autocomplete({
delay: 0,
minLength: 0,
source: $.proxy(this, "_source")
})
.tooltip({
tooltipClass: "ui-state-highlight"
});
this._on(this.input, {
autocompleteselect: function (event, ui) {
ui.item.option.selected = true;
this._trigger("select", event, {
item: ui.item.option
});
__doPostBack('<%= upnlTab.ClientID %>', this.element.attr("id"));
},
autocompletechange: "_removeIfInvalid"
});
},
_createShowAllButton: function () {
var input = this.input,
wasOpen = false;
$("<a>")
.attr("tabIndex", -1)
//.attr("title", "Show All Items")
//.tooltip()
.appendTo(this.wrapper)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("custom-combobox-toggle ui-corner-right")
.mousedown(function () {
wasOpen = input.autocomplete("widget").is(":visible");
})
.click(function () {
input.focus();
// Close if already visible
if (wasOpen) {
return;
}
// Pass empty string as value to search for, displaying all results
input.autocomplete("search", "");
});
},
_source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response(this.element.children("option").map(function () {
var text = $(this).text();
if (this.value && (!request.term || matcher.test(text)))
return {
label: text,
value: text,
option: this
};
}));
},
_removeIfInvalid: function (event, ui) {
// Selected an item, nothing to do
if (ui.item) {
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children("option").each(function () {
if ($(this).text().toLowerCase() === valueLowerCase) {
this.selected = valid = true;
return false;
}
});
// Found a match, nothing to do
if (valid) {
return;
}
// Remove invalid value
if (value != '') {
this.input
.val("")
.attr("title", value + " didn't match any item")
.tooltip("open");
this.element.val("");
this._delay(function () {
this.input.tooltip("close").attr("title", "");
}, 2500);
this.input.data("ui-autocomplete").term = "";
} else {
this.input.val("");
this.element.val("");
this.input.data("ui-autocomplete").term = "";
}
__doPostBack('<%= upnlTab.ClientID %>', this.element.attr("id"));
},
_destroy: function () {
this.wrapper.remove();
this.element.show();
}
});
})(jQuery);
}
C#
Based some validations I am calling this,
ddlStatus.Enabled = false;
There is an answer here and I am not be to get it work with my code.
Disable jQuery ComboBox when underlying DropDownList is disabled
This is how I have done it. please see the changes enclosed in * *.
(function ($) {
$.widget("custom.combobox", {
_create: function () {
this.wrapper = $("<span>")
.addClass("custom-combobox")
.insertAfter(this.element);
this.element.hide();
*select = this.element.hide();*
this._createAutocomplete(*select*);
this._createShowAllButton(*select*);
},
_createAutocomplete: function (*select*) {
var selected = this.element.children(":selected"),
select = this.element.hide(),
value = selected.val() ? selected.text() : "";
*var disabled = select.is(':disabled');*
this.input = $("<input>")
.appendTo(this.wrapper)
.val(value)
.attr("title", "")
.addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
.*attr('disabled', disabled)*
.autocomplete({
delay: 0,
minLength: 0,
source: $.proxy(this, "_source")
})
.tooltip({
tooltipClass: "ui-state-highlight"
});
this._on(this.input, {
autocompleteselect: function (event, ui) {
ui.item.option.selected = true;
this._trigger("select", event, {
item: ui.item.option
});
__doPostBack('<%= upnlTab.ClientID %>', this.element.attr("id"));
},
autocompletechange: "_removeIfInvalid"
});
},
_createShowAllButton: function (*select*) {
var input = this.input,
wasOpen = false;
*var disabled = select.is(':disabled');*
console.log(this.element.attr("id") + " : " + disabled);
$("<a>")
.attr("tabIndex", -1)
*.attr('disabled', disabled)*
//.attr("title", "Show All Items")
//.tooltip()
.appendTo(this.wrapper)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("custom-combobox-toggle ui-corner-right")
.mousedown(function () {
wasOpen = input.autocomplete("widget").is(":visible");
})
.click(function () {
*if ($(this).attr('disabled')) {
return false;
}*
input.focus();
// Close if already visible
if (wasOpen) {
return;
}
// Pass empty string as value to search for, displaying all results
input.autocomplete("search", "");
});
},
_source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response(this.element.children("option").map(function () {
var text = $(this).text();
if (this.value && (!request.term || matcher.test(text)))
return {
label: text,
value: text,
option: this
};
}));
},
_removeIfInvalid: function (event, ui) {
// Selected an item, nothing to do
if (ui.item) {
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children("option").each(function () {
if ($(this).text().toLowerCase() === valueLowerCase) {
this.selected = valid = true;
return false;
}
});
// Found a match, nothing to do
if (valid) {
return;
}
// Remove invalid value
if (value != '') {
this.input
.val("")
.attr("title", value + " didn't match any item")
.tooltip("open");
this.element.val("");
this._delay(function () {
this.input.tooltip("close").attr("title", "");
}, 2500);
this.input.data("ui-autocomplete").term = "";
} else {
this.input.val("");
this.element.val("");
this.input.data("ui-autocomplete").term = "";
}
__doPostBack('<%= upnlTab.ClientID %>', this.element.attr("id"));
},
_destroy: function () {
this.wrapper.remove();
this.element.show();
}
});
})(jQuery);

Adding jquery click event for UpdatePanel

I am using this code for binding asp.net gridview with right click contextmenu using jQuery but every time when I click it (use option in menu list) it reloads the page. What should I do if I want to use an UpdatePanel?
function fnView() {
var lnkView = document.getElementById('<%=lnkView.ClientID %>');
var hiddenField = document.getElementById('<%=fldProductID.ClientID %>');
hiddenField.value = $("div").filter("[type=ContextMenu]")[0].id.replace("Menu", "");
lnkView.click();
}
function fnDelete() {
var lnkDelete = document.getElementById('<%=lnkDelete.ClientID %>');
var hiddenField = document.getElementById('<%=fldProductID.ClientID %>');
hiddenField.value = $("div").filter("[type=ContextMenu]")[0].id.replace("Menu", "");
lnkDelete.click();
}
jQuery.fn.setEvents = function (e) {
var me1 = jQuery(this);
return this.each(function () {
var me = jQuery(this);
me.click(function (e) {
$("div").filter("[type=ContextMenu]").hide();
fnSetMenu(me.children(':first-child').text(), e.pageX, e.pageY);
});
});
};
function fnSetMenu(productID, left, top) {
if ($("#Menu" + productID).html() == null) {
var strMenuHTML = "<div type=\"ContextMenu\" id=\"Menu" + productID + "\" class=\"contextMenuClass\" mouseonmenu=\"1\"><table style='width:100%;'><tr><td onclick=fnView()>View Product</td></tr><tr><td onclick=fnDelete()>Delete Product</td></tr></table></div>";
$("body").append(strMenuHTML);
$.post("MenuHandler.ashx", {}, function (response) {
$("#Menu" + productID).html(response);
});
}
$("#Menu" + productID).css({ top: top + "px", left: left + "px" }).show();
}
$(document).ready(function () {
$("#gvProducts tr.ShowContext").setEvents();
}
);
$(document).click(function (e) {
$clicked = $(e.target);
if (!($clicked.parents().hasClass("ShowContext") || $clicked.hasClass("contextMenuClass") || $clicked.parents().hasClass("contextMenuClass"))) {
$("div").filter("[type=ContextMenu]").hide();
}
});
use jQuery's live function to bind an event inside updatepanel
or
go through this link
http://stackoverflow.com/questions/256195/jquery-document-ready-and-updatepanels

Categories

Resources