I gave a Devexpress GridView which represent addresses. Two cascading combobox (Governorate- Area). When the user choose a Governorate the area combo will filtered according to the Governorate chased. When the user doesn't know the corresponding Governorate for the area, he only start by choosing the area and the governorate combobox will fill with the right governorate.
In index.chtml
<script type="text/javascript">
function governorateCombo_SelectedIndexChanged(s, e) {
areaCode.PerformCallback();
}
function AreaCombo_BeginCallback(s, e) {
e.customArgs['governorateCode'] = governorateCode.GetValue();
}
function areaCombo_SelectedIndexChanged(s, e) {
governorateCode.PerformCallback();
}
function GovernorateCombo_BeginCallback(s, e) {
e.customArgs['areaCode'] = areaCode.GetValue();
}
function GovernorateCombo_EndCallback(s, e) {
benGeoGridView.Refresh();
var bla = '#Session["governorateCode"]';
var item = s.FindItemByValue(bla);
s.SetSelectedItem(item);
}
ComboboxGovernoratePartial.chtml
#Html.DevExpress().ComboBox(settings =>
{
settings.CallbackRouteValues = new { Controller = "benFile", Action = "ComboBoxGovernoratePartial" };
settings.Name = "governorateCode";
settings.Properties.TextField = "governorateName1";
settings.Properties.ValueField = "governorateCode";
settings.Properties.ValueType = typeof(string);
settings.Width = 220;
settings.Properties.EnableSynchronization = DefaultBoolean.False;
settings.Properties.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;
if (Thread.CurrentThread.CurrentCulture.Name.Substring(0, 2) == "ar")
{
settings.RightToLeft = DefaultBoolean.True;
}
settings.Properties.ClientSideEvents.BeginCallback = "GovernorateCombo_BeginCallback";
settings.Properties.ClientSideEvents.SelectedIndexChanged = "governorateCombo_SelectedIndexChanged";
settings.Properties.ClientSideEvents.EndCallback = "GovernorateCombo_EndCallback";
}).BindList(Model).Bind(ViewData["governorateCode"]).GetHtml()
In controller:
public ActionResult ComboBoxGovernoratePartial()
{
string areaCode = (Request.Params["areaCode"] != null) ? Request.Params["areaCode"] : "-1";
List<governorateName> governorateNames = new List<governorateName>();
governorateMaster governorateMaster = new governorateMaster();
if (areaCode != null)
{
Session["governorateCode"] = Masters.areaMasters.First(a => a.areaCode == areaCode).governorateCode; ;
ViewData["governorateCode"] = Masters.areaMasters.First(a => a.areaCode == areaCode).governorateCode;
governorateNames = Masters.governorateNames.Where(a => a.langCode.ToLower() == Thread.CurrentThread.CurrentCulture.Name.Substring(0, 2)).ToList();
}
return PartialView(governorateNames.ToList());
}
When the user choose the area, (in js) I call perform call back for the governorate combobox that the controller pick up the right governorate to populate in the governorate combobox. The problem is that when I send the governorate code in a ViewData it is always null. In a Session varible, the value of it is the one at page load not the updated one in the controller.
Any suggestion ?
Sorry for your time guys
For that, you can try:
TempData["yourVar"]
Related
i would like to display the roles in a dropdown from the offices which i have selected from a office dropdown.
but here is a problem here, the office selected dropdown is on page , but the dropdown which the roles should display is inside the ISSUEPOPUP BOX .
As of now we have implementation like all the roles are displaying ,we need to rearrrange that roles on basis of the office selected
i have angular code as
officeSelected() {
var selectedRegions = '';
var selectedOfficeId = '';
if (this.scope.selected.offices != undefined) {
selectedRegions = Array.prototype.map.call(this.scope.selected.offices, function (item) { return item.val; }).join(",");
selectedOfficeId = Array.prototype.map.call(this.scope.selected.offices, function (item) { return item.val; }).join(",");
this.setSupervisor(selectedRegions, 'office');
this.setTechnicians(selectedRegions, 'office');
this.scope.selected.regions = null;
this.scope.selected.subregions = null;
this.scope.selected.gbobranches = null;
this.scope.selected.supervisors = null;
this.scope.selected.technicians = null;
}
& in TS file , when we select a popupbox
getRoles() {
if (this.scope.selected != undefined && this.scope.selected.roles != undefined) {
this.scope.selected.roles = null;
}
//if (this.officeIds) {
// if (this.officeType) {
// }
//}
this.userService.getOfficeOrganizationalRoles(this.officeIds)
.then((response) => {
this.scope.roles = response.data;
});
}
please help me how to implement this feature
Consider this scenario where you want to retrieve a List or IEnumerable of the values of all the unchecked checkboxes in checkboxlist. this code gives me the value of all checked (now) or (previously). how can I get the values of unchecked (now) and (previously) with linq. thank you
private IEnumerable <string > selectedValues
{
get
{
if (ViewState ["selectedValues"] == null && chapp . SelectedIndex >=-1 )
{
ViewState ["selectedValues"]= chapp .Items.Cast <ListItem >()
.Where (li=>li.Selected )
.Select (li=>li.Value )
.ToList ();
}else
ViewState ["selectedValues"]= Enumerable .Empty <string >();
return (IEnumerable <string >)ViewState ["selectedValues"];
}
set {ViewState ["selectedValues"] = value ;}
}
protected void chapp_SelectedIndexChanged(Object sender, EventArgs e)
{
CheckBoxList c = (CheckBoxList)sender;
var oldselection = this.selectedValues;
var newSelection = c.Items.Cast<ListItem>()
.Where(li => li.Selected )
.Select(li => li.Value);
var unchangedItems = newSelection.Except(oldselection );
}
Based on you comment:
Let's say that you have aspx page which load all the applications you have (from active directory, DB or whatever), after that assigning all the applications which the current user have (also getting those applications from what ever) ... so in your Page_Load you will have something like below:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Load all applications
var apps = loadAllApplications();
//Load user applications
var myApps = loadUserApplications();
//Bind to checkboxlist, assuming my checkboxlist ID "chksApps"
chksApps.DataSource = apps.Select(x => new ListItem
{
Value = x.Id.ToString(),
Text = x.Name,
Selected = myApps.Any(a => x.Id == a)
});
chksApps.DataBind();
}
}
//lets say I have a Application class like that
public class Application
{
public int Id { get; set; }
public string Name { get; set; }
}
private List<int> loadUserApplications()
{
// if user already have "Paint", "Chrome" assigned
var myApps = new List<int>() { 2, 4 };
return myApps;
}
private List<Application> loadAllApplications()
{
//for testing I will create a dummy list of applications
var applications = new List<Application>() {
new Application { Id = 1, Name = "Visual Studio" },
new Application { Id = 2, Name = "Paint" },
new Application { Id = 3, Name = "Notepad" },
new Application { Id = 4, Name = "Chrome" }
};
return applications;
}
so till now the user will be able to check, uncheck what ever he want. so your checkboxlist AutoPostBack = False
so when he finish editing, assuming he will submit that to the server so he will have a submit button (lets say it's ID is "btnSave"
protected void btnSave_Click(object sender, EventArgs e)
{
//Load user applications
var myApps = loadUserApplications();
//get selected Application
var selectedApps = chksApps.Items.Cast<ListItem>()
.Where(x => x.Selected)
.Select(x => int.Parse(x.Value)).ToList();
// send request to owner to add those below apps for user "newSelectedApps"
var newSelectedApps = selectedApps.Except(myApps).ToList();
// send request to owner to remove those below apps "newUnSelectedApps"
var newUnSelectedApps = myApps.Except(selectedApps).ToList();
// those below are the unchanged apps "unChangedApps"
var unChangedApps = myApps.Intersect(selectedApps).ToList();
}
this is better than using ViewState for performance
I have a project where I report time on diffrent projects, and I am working on so I can delete a report incase I do it wrong, which is working decent.
When I go to the summery page of all my reports it lists all the dates, I click the date and it sends it to the TimeReport view like this:
http://localhost:9061/Reports/TimeReport/b604a74a-2034-4916-9534-57788db1e8e2
And than it checks if the ReportId has a value like this:
#if (Model.ReportId.HasValue)
{
<button type="button" class="btn btn-danger" data-toggle="modal" data-target="#basic">Ta bort!</button>
}
And if it exists a Remove button will appear, I click the remove button and it will remove the report. but the URL is still the same, so if I refresh the site my application will crash because it that ID no longer exists in the database.
if (form != null && form.AllKeys.Contains("delete"))
{
new DatabaseLayer().DeleteTimeReport(Guid.Parse(form["ReportId"]));
LoadDefaultSettings(projectData);
ViewData.Model = projectData;
ViewData["deleted"] = true;
return View();
}
This is the model that check if if the GUID exists.
public void SaveToDatabase(Guid consultantId)
{
using (DatabaseLayer db = new DatabaseLayer())
{
//Time report exists, delete it.
if (ReportId.HasValue)
{
db.DeleteTimeReport(ReportId.Value);
}
//Time report does not exist, create a new one.
else
{
ReportId = Guid.NewGuid();
}
Report report = new Report
{
FK_ConsultantID = consultantId,
FK_UserID = Constants.UserTreetop,
Date = Date,
TimeReportID = ReportId.Value
};
TimeReportData reportData = new TimeReportData
{
Absent = 0,
Description = "",
StartHour = Times.StartHour,
StartMinute = Times.StartMinute,
EndHour = Times.EndHour,
EndMinute = Times.EndMinute,
BreakHour = Times.BreakHour,
BreakMinute = Times.BreakMinute,
FK_TimeReportID = ReportId.Value,
TimeReportDataID = Guid.NewGuid()
};
TimeReportProject[] reportProjects = new TimeReportProject[Projects.Count];
for (int i = 0; i < Projects.Count; i++)
{
reportProjects[i] = new TimeReportProject
{
Description = Projects[i].Description,
FK_ProjectID = Projects[i].ProjectId,
FK_TimeReportID = ReportId.Value,
Hours = Projects[i].Hours.GetValueOrDefault(), //Projects[i].Hours.Value,
HourRate = db.GetProjectHourRate(Projects[i].ProjectId, Date, Projects[i].Hours.GetValueOrDefault()),
TimeReportProjectID = Guid.NewGuid()
};
}
db.InsertTimeReport(report, reportData, reportProjects);
}
}
And as it exists it does this
public void DeleteTimeReport(Guid timeReportId)
{
db.ExecuteStoreCommand(
#" DELETE FROM [Salesweb].[dbo].[TimeReportProject] WHERE FK_TimeReportID = #id;
DELETE FROM [Salesweb].[dbo].[TimeReportData] WHERE FK_TimeReportID = #id;
DELETE FROM [Salesweb].[dbo].[TimeReport] WHERE TimeReportID = #id;"
, new SqlParameter("#id", timeReportId));
db.SaveChanges();
}
This is the view when I pass in the guid I Want to delete as the guid has a value the remove button will appear.
But as I delete the project it will return to the same view. Like we can see the tabs is not showing up, so if I want the to show again I have to go to another view, and than back to the same view. And if I refresh it will crash due the guid dosen't exist in the DB.
And here is the whole controller, it's a bit messy right now.
public ActionResult TimeReport(FormCollection form, Guid? id)
{
ViewDataDictionary vd = new ViewDataDictionary
{
["projects"] = new DatabaseLayer().GetConsultantProjects(Constants.CurrentUser(User.Identity.Name)),
["id"] = 1,
["showDescription"] = true
};
ViewData["vd"] = vd;
NewTimeReportModel projectData = new NewTimeReportModel();
if (form != null && form.AllKeys.Contains("delete"))
{
new DatabaseLayer().DeleteTimeReport(Guid.Parse(form["ReportId"]));
LoadDefaultSettings(projectData);
ViewData.Model = projectData;
ViewData["deleted"] = true;
return RedirectToAction("Index");
}
if (id.HasValue && (form == null || form.AllKeys.Length == 0))
{
using (DatabaseLayer db = new DatabaseLayer())
{
var timeReport = db.GetTimeReport(id.Value);
projectData = new NewTimeReportModel(timeReport);
if (projectData.Projects.Count == 1)
projectData.Projects[0].Hours = null;
}
}
else if (form == null || form.AllKeys.Length == 0)
{
LoadDefaultSettings(projectData);
}
else
{
//Get's all the dates from the view and formates them to look like yy-mm-dd so we can parse it to a datetime.
string[] dates = FormateDate(form["date"]);
//Loops over all the dates and saves the dates to the database.
projectData = ReportDates(form, projectData, dates);
//Loads default settings if all dates been reported.
LoadDefaultSettings(projectData);
}
//Get's and lists all the missing days
ListAllMssingDays();
ViewData.Model = projectData;
return View();
}
Recommended thing to do in such cases is run redirect to some default URL, like the summary page. Guessing that you have Summary action, that should be something like:
if (form != null && form.AllKeys.Contains("delete"))
{
new DatabaseLayer().DeleteTimeReport(Guid.Parse(form["ReportId"]));
return RedirectToAction("Summary", "Reports");
}
Note that this will do a client-side redirect, so to say - this will do a response with code 302 and new URL /Reports/Summary. This is usually a desired behavior though.
The exception you're getting is because your code assumes the item you're deleting will exist.
Change
return db.TimeReports.Where(x => x.TimeReportID == timeReportId).Single();
To
return db.TimeReports.Where(x => x.TimeReportID == timeReportId).SingleOrDefault();
Which will return null if your Where clause returns 0 items.
Then wherever in your code you're calling GetTimeReport() you need to check for and handle null.
I have a standard DevExpress MVCxGridView bound to a DataTable, which is just a bunch of boolean values with the first column "SS" being a string code which is the datakey. I loop through all the columns and dynamically create the gridview columns. The grid that is displayed is a bunch of checkboxes which are options that can be configured.
I have a jquery js file that requires the data-* attributes to be set for these cells in order to inject the necessary functionality. I want to know how to add "data-*" attributes to each of the TD cells. "data-ss" being the datakey in the first column, and "data-wm" being the workmode in the column.
My Razor view code is as follows:
#model System.Data.DataTable
#{
var gv = Html.DevExpress().GridView(
settings =>
{
settings.Name = "gv";
settings.Enabled = true;
settings.KeyFieldName = "SS";
settings.CallbackRouteValues = new { Controller = "Test", Action = "DataBindingPartial" };
settings.Settings.HorizontalScrollBarMode = ScrollBarMode.Auto;
settings.Settings.VerticalScrollBarMode = ScrollBarMode.Auto;
settings.Settings.VerticalScrollableHeight = 200;
settings.SettingsPager.Mode = DevExpress.Web.ASPxGridView.GridViewPagerMode.ShowAllRecords;
MVCxGridViewBandColumn currentBand = null;
foreach (System.Data.DataColumn c in Model.Columns)
{
if (c.ColumnName == "SS")
{
DevExpress.Web.ASPxGridView.GridViewColumn column = settings.Columns.Add(c.ColumnName);
column.Caption = "SS";
column.CellStyle.CssClass = "ss_head";
column.HeaderStyle.CssClass = "ss_head_caption";
column.HeaderStyle.Cursor = "pointer";
}
else
{
// Get Column Definition retreives information based on the column name
// definition.ActivityType = "act" if activity or "dg" if DataGathering
// definition.WorkMode = abbreviated name of activity
// definition.Description = long description of activity
var definition =
TestModel.DefinitionColumn.GetColumnDefinition(c.ColumnName);
if (currentBand == null || currentBand.Name != definition.ActivityType)
{
currentBand = settings.Columns.AddBand();
currentBand.Name = definition.ActivityType;
currentBand.Caption = definition.ActivityType == "act" ? "Activity" : "Data Gathering";
currentBand.HeaderStyle.CssClass = String.Format("workmode_col workmode_{0}", definition.ActivityType);
}
DevExpress.Web.ASPxGridView.GridViewColumn column =
currentBand.Columns.Add(c.ColumnName, MVCxGridViewColumnType.CheckBox);
column.Caption = definition.WorkMode;
column.ToolTip = definition.Description;
column.Visible = true;
column.HeaderStyle.Cursor = "pointer";
column.CellStyle.CssClass = String.Format("workmode_{0} workmode_selectable workmode_col", definition.ActivityType);
column.HeaderStyle.CssClass = String.Format("workmode_{0} workmode_col", definition.ActivityType);
column.Width = 35;
}
}
});
var gvBound = gv.Bind(Model);
gvBound.Render();
}
Thank you Mikhail.
Using this I was able to add a settings configuration to set the data-* attributes:
settings.HtmlDataCellPrepared = (sender, e) =>
{
e.Cell.Attributes.Add(
"data-wm",
e.DataColumn.Caption
);
e.Cell.Attributes.Add(
"data-ssco",
e.KeyValue.ToString()
);
};
It is possible to use GridViewSettings.HtmlDataCellPrepared event to assign the required attributes. Check this SO thread.
I got an ActionResult TabNotes which returns a View for a tab which shows notes from a database in a grid. On the tab is a button for ActionResult CreateNote, which returns a PartialView and after saving the note I redirect back to the ActionResult TabNotes with
return RedirectToAction("TabNotes", new { modelEntity = "Phrase", id = itemId});
However, when it goes to the action result TabNotes using this redirect it does not show the grid. The javascript gives the following error
Uncaught ReferenceError: $ is not defined (anonymous function)
Uncaught ReferenceError: ko is not defined (anonymous function)
This does not happen the first time it goes to ActionResult. Using breakpoints the following part of the ActionResult TabNotes:
[...]
Model.Grid.url = Url.Action("TabNoteData", new { id = Model.meta.entity, itemId = Model.meta.id.Value});
}
return View("TabNotes", Model);
}
gives the same input values in Model for the first time and the second time. Where can this error come from?
Edit: Firebug shows the following errors:
prompt aborted by user
throw Components.Exception...by user", Cr.NS_ERROR_NOT_AVAILABLE); nsPrompter.js (regel 462 <Systeem>
$ is not defined
$(document).ready(function(){$('#tblTN...tes/44?cmd=refresh" id="TNPhrase44"> 44?mod...=Phrase (regel 2)
ko is not defined
var viewModel=ko.mapping.fromJ...],"buttons":[],"PostAction":null}}); 44?mod...=Phrase (regel 12)
Below is the javascript and code
#model test.Web.Framework.Areas.Administration.Models.TabNotesModel
#using (UI.DocumentReadyScript())
{
if (Model.meta.id.HasValue)
{
UI.jQuery("#tbl" + Model.meta.modelname).flexigrid(Model.Grid);
}
}
<form method="post" action="#Url.Action("TabNotes", new { cmd = "refresh" })" id="#Model.meta.modelname">
<div class="ui-state-highlight ui-corner-all highlight" data-bind="visible: meta.message">
<span class="ui-icon ui-icon-info"></span><strong data-bind="text: meta.message">
</strong>
</div>
#using (UI.BeginBlock("Administation.TabNotes", UI.Label("Notes", "Notes").ToString(), test.Web.Framework.Core.enumIcons.pencil, false, false))
{
<table id="#("tbl" + Model.meta.modelname)">
</table>
}
</form>
<script type="text/javascript">
(function() {
var viewModel=ko.mapping.fromJS(#Html.Raw(UI.JavascriptEncode(Model)));
viewModel.getData=function() { return ko.mapping.toJSON( this ); };
viewModel.setData=function(data){
$('#tbl'+this.meta.modelname()).flexigrid( data.Grid);
ko.mapping.updateFromJS(this,data);
};
$('##Model.meta.modelname').koform({viewmodel: viewModel , validate : {errorElement:'p' } } );
$('##Model.meta.modelname').koform('applyBindings');
$('#load-partial').click(function() {
$('#partial').load('#Url.Action("CreateNote", "Entity", new {itemId = #Model.meta.id, modelEntity = "Phrase"})');
});
})();
</script>
<div id="partial"></div>
<button type="button" id="load-partial">Create Note</button>
'
public ActionResult CreateNote(
[ModelBinder(typeof(Models.JsonModelBinder))]
NoteModel Model, string cmd, long? itemId, string modelEntity)
{
if (cmd == "Save")
{
Model.meta.message = "Note saved";
test.Database.User User = UserRepository.GetUser(1);
Entity entity = NotesRepository.GetEntity("Phrase");
NotesRepository.StoreNote(Model.subject, Model.text, User, entity, itemId);
return RedirectToAction("TabNotes", new { modelEntity = "Phrase", id = itemId});
}
Model.meta.modelname = "CreateNote";
Model.meta.JsViewModelType = "EditNoteModel";
Model.meta.PostAction = Url.Action("CreateNote", new { cmd = "Save", itemId = itemId});
return PartialView("CreateNotePartial",Model);
}
'
public ActionResult TabNotes([ModelBinder(typeof(Models.JsonModelBinder))]
TabNotesModel Model, string cmd, string modelEntity, long? id)
{
if (modelEntity != null)
{
Model.meta.entity = modelEntity;
}
Entity entity = NotesRepository.GetEntity(Model.meta.entity);
if (id.HasValue)
{
Model.meta.id = id;
}
if (Model.meta.id.HasValue)
{
Model.meta.modelname = "TN" + Model.meta.entity + Model.meta.id.Value.ToString();
Dictionary<string, object> defaultValues = new Dictionary<string, object>();
defaultValues.Add("Entity", entity.EntityId);
defaultValues.Add("ItemId", Model.meta.id.Value);
Entity noteEntity = NotesRepository.GetEntity("Note");
var grid = UI.GetEntityFlexiGrid(noteEntity, true, true, true, true, defaultValues);
grid.buttons.Clear();
//grid.buttons.Add(new Button { onpress = "CreateNote", action = Url.Action("CreateNote"), name = "CreateNote", postdata = new { meta = Model.meta }});
grid.title = "";
Model.Grid = grid;
Model.Grid.url = Url.Action("TabNoteData", new { id = Model.meta.entity, itemId = Model.meta.id.Value});
}
return View("TabNotes", Model);
}
'
public GridResult TabNoteData(string id, long itemId, FlexigridRequest request, string cmd)
{
GridResult returnValue = null;
var entity = NotesRepository.GetEntity(id);
Entity noteEntity = NotesRepository.GetEntity("Note");
//var Acess = UIRepository.GetEntityAccess(id);
FlexigridConfiguration grid;
Dictionary<string, object> defaultValues = new Dictionary<string, object>();
defaultValues.Add("Entity", entity.EntityId);
defaultValues.Add("ItemId",itemId);
grid = UI.GetEntityFlexiGrid(noteEntity, true, true, true, true, defaultValues);
IQueryable q = NotesRepository.GetNotes(entity.EntityId, itemId);
var sortField = entity.EntityFields.SingleOrDefault(c => c.Name == request.sortname);
if (sortField == null)
{
request.sortname = grid.sortname;
}
IQueryable qdata = null;
if (!string.IsNullOrEmpty(request.sortname) && request.sortname != "undefined")
{
switch (request.sortorder)
{
case enumFlexigridRequestSortOrder.asc:
qdata = q.OrderBy(request.sortname + " ascending");
break;
case enumFlexigridRequestSortOrder.desc:
qdata = q.OrderBy(request.sortname + " descending");
break;
}
}
if (!string.IsNullOrEmpty(request.query) && !string.IsNullOrEmpty(request.qtype))
{
qdata = qdata.Where(request.qtype.SanitizeFieldExpression() + ".Contains(#0)", request.query);
}
if (request.q != null && request.q.Length > 0)
{
for (int i = 0; i < request.q.Length; i++)
{
var type = UIRepository.GetType(id);
var property = type.GetProperty(request.q[i]);
System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(property.PropertyType);
string sv = request.v[i];
if (sv == null || sv == "null")
{
qdata = qdata.Where(request.q[i].SanitizeFieldExpression() + "=#0", (object)null);
}
else
{
object v = tc.ConvertFromString(sv);
qdata = qdata.Where(request.q[i].SanitizeFieldExpression() + "=#0", v);
}
}
}
string settingName = "Grid." + id + ".Rp";
var setting = UIRepository.GetQuery<test.Database.UserSetting>().SingleOrDefault(uc => uc.CreatedById == CurrentUser.UserId && uc.Name == settingName);
if (setting == null)
{
setting = UIRepository.Create<test.Database.UserSetting>();
setting.Name = settingName;
setting.Value = request.rp.ToString();
UIRepository.Add(setting);
}
else
{
if (request.rp.ToString() != setting.Value)
{
setting.Value = request.rp.ToString();
UIRepository.Update(setting);
}
}
int rowId = 0;
var datarows = new List<object>();
foreach (var record in qdata.Skip((request.page - 1) * request.rp).Take(request.rp).GetData())
{
var cellValues = new List<object>();
foreach (var gc in grid.colModel.OrderBy(c => c.di))
{
cellValues.Add(gc.ToString(UI, record));
}
var row = new { id = rowId, cell = cellValues.ToArray() };
datarows.Add(row);
rowId++;
}
returnValue = Grid(request.page, qdata.Count(), datarows.ToList());
return returnValue;
}
That error can only be caused be one of three things:
Your JavaScript file is not being properly loaded into your page
You have a botched version of jQuery. This could happen because someone edited the core file, or a plugin may have overwritten the $ variable.
You have JavaScript running before the page is fully loaded, and as such, before jQuery is fully loaded.
You should check the Firebug net panel to see if the file is actually being loaded properly. If not, it will be highlighted red and will say "404" beside it. If the file is loading properly, that means that the issue is number 2.
Make sure all javascript code is being run inside a code block such as:
$(document).ready(function () {
//your code here
});
This will ensure that your code is being loaded after jQuery has been initialized.
One final thing to check is to make sure that you are not loading any plugins before you load jQuery. Plugins extend the "$" object, so if you load a plugin before loading jQuery core, then you'll get the error you described.
So to avoid that you can use a "bodyguard" function like the following:
( function($) {
//We can now use $ as I implemented the bodyguard!
$(document).ready(function() {
//your code...
});
} ) ( jQuery );