High Chart Issue on VS 2008 - c#

I have a serious Issue :(, I'm using High Charts controls on VS 2008 and everytime I made run to the web application I got that "Silly" RunTime Error :
missing compiler required member 'system.runtime.compilerservices.extensionattribute.ctor.
I don't know the reason for that and I will appreciate any help !.

First of All I would like to thank everyone who commented on my stupid issue.Especially, wergeld (#wergeld),who gave me the first melody of the symphony:)...
My solution is a work around on that stupid compile error by writing the Javascript implementation of the chart using StringBuilder Class and this is the main idea of the work around.
lets stop chit chat :) and look at my humble work around:
First, I inserted all my Chart Implementation into a single class called "ChartImplementor.Cs" as following:
public enum ChartTypes
{
pie,
column,
bar
}
public class ChartImplementor
{
#region Member Variables
string _title = String.Empty;
string _subTitle = String.Empty;
string _YTitle = string.Empty;
string _XTitle = string.Empty;
#endregion
#region Properties
public string ChartTitle
{
set { _subTitle = value; }
get { return _subTitle; }
}
public string ChartSubTitle
{
set { _title = value; }
get { return _title; }
}
public string YTitle
{
set { _YTitle = value; }
get { return _YTitle; }
}
public string XTitle
{
set { _XTitle = value; }
get { return _XTitle; }
}
#endregion
public string GenerateChartJS(ChartImplementor _chartObj,
ChartTypes _chartType,
Dictionary<object, object> _myXYDictionary, string _divID)
{
string newX_String = string.Empty;
string newY_String = string.Empty;
string ChartScript = string.Empty;
StringBuilder builder = new StringBuilder();
if (_chartType == ChartTypes.column || _chartType == ChartTypes.bar)
{
foreach (KeyValuePair<object, object> pair in _myXYDictionary)
{
string newXValue = String.Format("'{0}',", _myXYDictionary.Keys);
newX_String += newXValue;
}
string XAxisData = string.Format("[{0}]", newX_String);
builder.Append("<script language='javascript' type='text/javascript'>");
builder.Append("$(function () {");
builder.Append("$('#" + _divID + "').highcharts({");
builder.Append("chart: {type:'" + _chartType + "'},");
builder.Append("title: {text:'" + _chartObj.ChartTitle + "'},");
builder.Append("subtitle: {text:'" + _chartObj.ChartSubTitle + "'},");
builder.Append("xAxis: {title: { text:'" + _chartObj.XTitle + "'},categories:" + XAxisData + ",labels:{enabled:false}},");
builder.Append("yAxis: { min: 0, title: { text:'" + _chartObj.YTitle + "'}},");
builder.Append("tooltip: {headerFormat: '<span style=font-size:10px></span>");
builder.Append("<table style=direction: rtl>',");
builder.Append("pointFormat: '<tr><td style=color:{series.color};padding:0>{series.name}: </td><td style=padding:0><b>{point.y:.1f}</b></td></tr>',");
builder.Append("footerFormat: '</table>',");
//builder.Append("shared: true,");
builder.Append("useHTML: true},");
builder.Append("plotOptions: { column: { pointPadding: 0.2, borderWidth: 0}},");
builder.Append("series:[");
foreach (KeyValuePair<object, object> pair in _myXYDictionary)
{
string newXValue = String.Format("'{0}'", pair.Key);
builder.Append("{ name:");
builder.Append("" + newXValue + "");
builder.Append(",data: ");
builder.Append("[" + pair.Value + "]},");
}
builder.Append("]});");
builder.Append("});");
builder.Append("</script>");
ChartScript = builder.ToString();
}
else if (_chartType == ChartTypes.pie)
{
builder.Append("<script language='javascript' type='text/javascript'>");
builder.Append("$(function () {");
builder.Append("$('#" + _divID + "').highcharts({");
builder.Append("chart: {plotBackgroundColor: null,plotBorderWidth: null,plotShadow: false},");
builder.Append("title: {text:'" + _chartObj.ChartTitle + "'},");
//{series.name}:
builder.Append("tooltip: { pointFormat: '<b{point.percentage:.1f}%</b>'},");
builder.Append("plotOptions: { pie: {allowPointSelect: true,cursor: 'pointer',dataLabels: { enabled: true, color: '#000000',connectorColor: '#000000', format: '<b>{point.name}</b>: {point.percentage:.1f} %'}}},");
builder.Append("series:[{type: 'pie',data:[");
foreach (KeyValuePair<object, object> pair in _myXYDictionary)
{
string newXValue = String.Format("['{0}',{1}],", pair.Key, pair.Value);
builder.Append(newXValue);
}
builder.Append("]}] });");
builder.Append("});");
builder.Append("</script>");
ChartScript = builder.ToString();
}
return ChartScript;
}
}
As it can be seen from the class that the target method contains 4 parameters:
1.An instance of the ChartImplementer Class.
2.An Object from ChartTypes Enumeration.
3.An Object od a dictionary that its key and value are from an Object DataTypes(This Dictionary will take the X/Y Cordinates of the chart for Binding it).
4.The ID of the Control which will populate the Chart staff.
I have implemented the Datasource of the chart in a Dictionary Control and I passed it as a parameter in the Target Page As Following:
protected void ImageButtonPopulateChart_Click(object sender, ImageClickEventArgs e)
{
int? genderID = null;
Dictionary<object, object> myXyDataObjects = new Dictionary<object, object>();
ChartImplementor charting = new ChartImplementor()
{
ChartTitle = "A digram illustrates Employees ",
ChartSubTitle = "HSBC Bank.",
XTitle = "Employees",
YTitle = "Salaries"
};
var chartQuery = SchoolDC.usp_Chart_Report(SchoolID, genderID, statusID).ToList();
foreach (var item in chartQuery)
{
myXyDataObjects.Add(item.LevelName, item.stCount);
}
ScriptManager.RegisterStartupScript(UpdatePanel1,
UpdatePanel1.GetType(),
"script",charting.GenerateChartJS(charting, ChartTypes.column, myXyDataObjects, "container"), // container is the ID of the Div Control which will populate the Chart.
false);
}
This is the .aspx page :
<body>
<form id="form1" runat="server">
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto">
</div>
<asp:ImageButton ID="ImageButtonPopulateChart" runat="server" onclick="ImageButtonPopulateChart_Click" />
</form>
</body>
N.B: To be able to populate the Chart you need to invoke Highcharts.Js Script, and Exporting.Js Script which it is responsible for exporting the Chart in many different Formats(I like that feature:) ).
RIP Steve Jobs said,We're just enthusiastic about what we do.I'm very enthusiastic about sharing my solution to you here, so please if you revise my code and find something that can make the code looks more better or even any other crazy idea don't hesitate to advice me :).
I wish a happy day for everyone.

Related

how to implement Treeview in razor page

previous quest
i make tree view in razor page
As I tried to call multiple tree views simultaneously in cshtml, I ended up using a recursive function.
program sequence
Get all tree data from DB
Bind tree data to TreeNode
Display in html using recursive function
So while I was looking for it, I found something that can make html directly in the back and I'm going to use it.
When creating jsonresult, "There was a case where the js function itself was not recognized due to a problem.
I want to know if there is a way
Questions
Is the way I'm building my tree a very strange way now?
public class TreeNode
{
public List<TreeNode> subTreeNodes { get; set; }
public string dataName { get; set; }
public bool deployment { get; set; }
public string board_id { get; set; }
public TreeNode(string dName)
{
dataName = dName;
deployment = false;
}
}
cshtml.cs
public IActionResult OnGet()
{
//if(session)
List<TreeNode> treeData;
IQueryable<tbl_tree> iqueryTree;
iqueryTree = _context.tbl_tree.Where(x => x.upcode == "AAAAAA");
var datas = iqueryTree.ToList();
tree_List = new List<TreeNode>();
for (int i = 0; i < datas.Count; i++)
{
TreeNode treeNode = new TreeNode(datas[i].name);
treeNode.subTreeNodes = ConstructorData(datas[i].icd11);
treeNode.board_id = datas[i].icd11;
tree_List.Add(treeNode);
}
TempData.Set("TreeData", tree_List);
jsonData = UpdateRecursiveData(tree_List[1]);
return Page();
}
public List<TreeNode> ConstructorData(string str)
{
List<TreeNode> treeNodes = new List<TreeNode>();
IQueryable<tbl_tree> iqueryTree;
iqueryTree = _context.tbl_tree.Where(x => x.upcode == str);
var datas = iqueryTree.ToList();
for (int i = 0; i < datas.Count; i++)
{
TreeNode treeNode = new TreeNode(datas[i].name);
treeNode.board_id = datas[i].icd11;
treeNode.subTreeNodes = ConstructorData(datas[i].icd11);
treeNodes.Add(treeNode);
}
return treeNodes;
}
How will you package "in jsonresult?"
JsonResult UpdateRecursiveData(TreeNode tn)
{
JsonResult jsonResult = new JsonResult(
"<input type = 'checkbox' onclick = requestMyAction( '" +tn.board_id+"', this.checked, 'loader-"+tn.dataName+"');' />" +
"<div class='loader' style='display: none;' id='loader-'" +tn.dataName+ "'> "+tn.dataName+ "</div>" +
"<br />");
//if (tn.deployment)
//{
//for (int i = 0; i<tn.subTreeNodes.Count; i++)
// UpdateRecursiveData(tn.subTreeNodes[i]);
//}
return jsonResult;
}
this cshtml
<input type="checkbox"
onclick="requestMyAction('#Model.tree_List[0].board_id', this.checked,
'loader-#Model.tree_List[0].dataName');" />
<div class="loader" style="display: none;" id="loader-#Model.tree_List[0].dataName">
#Model.tree_List[0]
</div>
<div id="data">
#Html.Raw(Model.jsonData.Value)
</div>
remove all
this error is syntax error js complier is not working in VS studio
string strResult =
"<div style='padding: 0 0 0 10px ;display:"+defaultView+"'id='"+tn.dataName+tn.upCode+"'>" +
"<input type='checkbox'style='visibility:"+subCheck+";'onclick=requestMyAction('"+tn.icd11+"',this.checked,'"+tn.dataName+tn.upCode+"');>" +
"<span onclick = 'CallViewBorad("+tn.board_Id + ")' >"+tn.dataName+" </span>";

How to create 'n' child objects and parent at the same view?

I'm using asp.net mvc razor, and I'm making a view to create a parent's object, but along creating the parent I need to create 'n' child objects. How can I do this exactly?
I will reinforce that I'm not expecting to display the object's, I need to create them in one go, I say this only because I saw too many misunderstanding in my research.
Let me explain exactly what i need to do:
I have a model called 'Car', this model have a child element: ICollection< Extra >, when the user will insert a new 'Car' he may be capable of insert 'Extra' stuff before inserting the 'Car' to the database. And the 'Extra' could have N elements, so it's not fixed.
My model as example:
[Table("Car")]
public partial class Car
{
[Key]
public int IdCar { get; set; }
[Required]
[StringLength(10)]
[Display(Name = "Car")]
public string DsCar { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Extra> Extra{ get; set; }
}
Here's a view example of what i want to do that could help:
Insert Page
I wish to avoid the page refreshing effect if possible too.
After some researching I did not find anything suitable for my case, so I ended doing some code by myself.
(I was not able to search to much, I believe there must be a better answer somewhere)
As I want to make them reusable i created them in a partial view.
<div class="form-group">
#{
TempData["ParentToken"] = ViewBag.Token;
Html.RenderAction("EstoqueOpcional", "Estoques");
}
</div>
In my partial view I created an AjaxForms:
#using (Ajax.BeginForm("EstoqueOpcionalCreate", new AjaxOptions() { OnSuccess = "RegistroAdicionadoOpcional()", OnFailure = "ConectionFailed()", HttpMethod = "Post" })){
#Html.Hidden("PageToken", (object)TempData["ParentToken"])
<!-- MY FIELDS -->
<input type="submit" value="Atualizar" class="btn btn-save" />
...
I have a page token in every page so I can create TempDatas using them without problem of the user opening multiple tabs of the same view. (ViewBag's isn't available because I'm not able to send anything back to the page).
Those are the scripts I created to control the display and stuff. (Most of them are still strongly typed as I still not refined my code yet)
<script>
function RegistroAdicionadoOpcional() {
var newData = $("#dsopcional").val();
var pass = true;
$("#tableEstoqueOpcional .CheckData").each(function () {
if ($(this).html() == newData)
pass = false;
});
if (pass) {
$("#tableEstoqueOpcional").append("<tr><td class=\"CheckData\">" + newData + "</td>" +
"<td class=\"grid-cell temp-cell\" style=\"padding: 0px !important;\">" + "Remover" + "</td></tr>");
$("#dsopcional").val("");
$("#dsopcional").focus();
}
else {
Message("Error", "Esse valor já foi inserido.");
$("#dsopcional").focus();
}
}
function RemoveDataOpcional(value) {
$.ajax({
url: "/Estoques/RemoverOpcional",
data: { opcional: value, PageToken: $("#PageToken").val() },
cache: false,
type: "POST",
timeout: 5000,
success: function (data) {
if (data == "True") {
$("#tableEstoqueOpcional .CheckData").each(function () {
if ($(this).html() == value)
$(this).parent('tr').remove();
});
}
else
Message("Error", "Não foi possível remover o valor escolhido, tente atualizar a página.");
},
error: function (reponse) {
Message("Error", "Não foi possível remover o valor selecionado, se o erro persistir tente recarregar a página.");
}
});
}
#{
var regs = "";
if (TempData["EstoqueOpcional"] != null)
{
foreach (var item in (List<Models.EstoqueOpcional>)TempData["EstoqueOpcional"])
{
regs += "<tr><td class=\\\"CheckData\\\">" + item.DsOpcional + "</td>" +
"<td class=\\\"grid-cell temp-cell\\\" style=\\\"padding: 0px !important;\\\">" + "Remover" + "</td></tr>";
}
}
TempData["DisplayEstoque"] = regs;
}
$(document).ready(function () {
var text = "#Html.Raw(HttpUtility.HtmlDecode(TempData["DisplayEstoque"].ToString()))";
$("#tableEstoqueOpcional").append(text);
});
In my controller I created those methods to control the values in the TempData:
public ActionResult EstoqueOpcional()
{
return PartialView(new EstoqueOpcional());
}
[HttpPost]
public bool EstoqueOpcionalCreate(EstoqueOpcional estoqueOpcional, string PageToken)
{
List<EstoqueOpcional> estoqueOpcionals = new List<EstoqueOpcional>();
if (TempData["EstoqueOpcional" + PageToken] != null)
estoqueOpcionals.AddRange((List<EstoqueOpcional>)TempData["EstoqueOpcional" + PageToken]);
if (estoqueOpcionals.Where(x => x.DsOpcional == estoqueOpcional.DsOpcional).Count() == 0)
estoqueOpcionals.Add(estoqueOpcional);
TempData["EstoqueOpcional" + PageToken] = estoqueOpcionals;
return true;
}
public bool RemoverOpcional(string opcional, string PageToken)
{
try
{
if (TempData["EstoqueOpcional" + PageToken] != null)
{
List<EstoqueOpcional> estoqueOpcionals = (List<EstoqueOpcional>)TempData["EstoqueOpcional" + PageToken];
estoqueOpcionals.RemoveAll(x => x.DsOpcional == opcional);
TempData["EstoqueOpcional" + PageToken] = estoqueOpcionals;
}
return true;
}
catch
{
return false;
}
}
In the update button button of my main model I have done like this:
List<EstoqueOpcional> estoqueOpcionals = new List<EstoqueOpcional>();
if (TempData["EstoqueOpcional" + PageToken] != null)
estoqueOpcionals.AddRange((List<EstoqueOpcional>)TempData["EstoqueOpcional" + PageToken]);
foreach (var estoqueopcional in estoqueOpcionals)
{
estoqueopcional.CdEstoque = estoque.CdEstoque;
EstoqueOpcional estoqueopcionaltemp = db.EstoqueOpcional.Where(x => x.DsOpcional == estoqueopcional.DsOpcional).FirstOrDefault();
if (estoqueopcionaltemp == null)
db.EstoqueOpcional.Add(estoqueopcional);
}
foreach (var item in db.EstoqueOpcional.Where(x => x.CdEstoque == estoque.CdEstoque).ToList()
.Where(x => !estoqueOpcionals.Any(y => y.DsOpcional == x.DsOpcional)).ToList())
{
db.EstoqueOpcional.Remove(item);
}
The create method it's very familiar with the update one.
I still believe there must be a easier way to do this, but this was suitable for me.
Image Result
Any advice or suggestion is welcome.
Thanks.

Extending Internal Link and External Link to allow selection of Images

I need to extend selection of external and Internal Link and provide a image selection.
Please see the snapshot in the below :
Here the above snapshot allows you to add properties for External Link.In the same popup can we add a field Called Image(as shown in screenshot) which will allow user to select images from the media library??
Thanks,
Suhas
If you are using Sitecore 7.2 and want to update internal link then you need to do with Sitecore speak and in case of external link simply update under /shell/Applications/Dialogs/ExternalLink folder.
To render this field create CustomLinkRenderer class and inheri this class by LinkRenderer of Sitecore.Kernel.dll.
Please see below code for CustomLinkRenderer
public class CustomLinkRenderer : LinkRenderer
{
public CustomLinkRenderer(Item item)
: base(item)
{
}
public override RenderFieldResult Render()
{
string str8;
SafeDictionary<string> dictionary = new SafeDictionary<string>();
dictionary.AddRange(this.Parameters);
if (MainUtil.GetBool(dictionary["endlink"], false))
{
return RenderFieldResult.EndLink;
}
Set<string> set = Set<string>.Create(new string[] { "field", "select", "text", "haschildren", "before", "after", "enclosingtag", "fieldname" });
LinkField linkField = this.LinkField;
if (linkField != null)
{
dictionary["title"] = StringUtil.GetString(new string[] { dictionary["title"], linkField.Title });
dictionary["target"] = StringUtil.GetString(new string[] { dictionary["target"], linkField.Target });
dictionary["class"] = StringUtil.GetString(new string[] { dictionary["class"], linkField.Class });
}
string str = string.Empty;
string rawParameters = this.RawParameters;
if (!string.IsNullOrEmpty(rawParameters) && (rawParameters.IndexOfAny(new char[] { '=', '&' }) < 0))
{
str = rawParameters;
}
if (string.IsNullOrEmpty(str))
{
Item targetItem = this.TargetItem;
string str3 = (targetItem != null) ? targetItem.DisplayName : string.Empty;
string str4 = (linkField != null) ? linkField.Text : string.Empty;
str = StringUtil.GetString(new string[] { str, dictionary["text"], str4, str3 });
}
string url = this.GetUrl(linkField);
if (((str8 = this.LinkType) != null) && (str8 == "javascript"))
{
dictionary["href"] = "#";
dictionary["onclick"] = StringUtil.GetString(new string[] { dictionary["onclick"], url });
}
else
{
dictionary["href"] = HttpUtility.HtmlEncode(StringUtil.GetString(new string[] { dictionary["href"], url }));
}
// Add onclick attribute for Google event tracking
dictionary["onclick"] = LinkField.GetAttribute("on_click");
StringBuilder tag = new StringBuilder("<a", 0x2f);
foreach (KeyValuePair<string, string> pair in dictionary)
{
string key = pair.Key;
string str7 = pair.Value;
if (!set.Contains(key.ToLowerInvariant()))
{
FieldRendererBase.AddAttribute(tag, key, str7);
}
}
tag.Append('>');
if (!MainUtil.GetBool(dictionary["haschildren"], false))
{
if (string.IsNullOrEmpty(str))
{
return RenderFieldResult.Empty;
}
tag.Append(str);
}
return new RenderFieldResult { FirstPart = tag.ToString(), LastPart = "</a>" };
}
}
You need to extend this class as per your need to render image.
If you are talking about a whole field and not just an external link inside of a rich text field, you should create a custom field based on the documentation to do so in SDN:
http://sdn.sitecore.net/Articles/API/Creating%20a%20Composite%20Custom%20Field.aspx
You can inherit most functionality from the current link field.
You can actually extend any dialog by editing the xml files in /shell/Applications/Dialogs
In another thread I have shown how to add a maxlength to the title field, that should help you get on your way: Limit number of Characters entered for Link Title Field in General Link

How to get the value of the textbox which created dynamically with the Raduploader in code behind?

I use the AsyncUpload
<telerik:RadAsyncUpload runat="server" ID="rada_attach" OnClientFileUploaded="onClientFileUploaded"
MultipleFileSelection="Disabled" InitialFileInputsCount="1" MaxFileInputsCount="1"
Width="100%" />
function onClientFileUploaded(radAsyncUpload, args) {
var row = args.get_row(),
inputName = radAsyncUpload.getAdditionalFieldID("TextBox"),
inputType = "text",
inputID = inputName,
input = createInput(inputType, inputID, inputName),
label = createLabel(inputID),
br = document.createElement("br");
row.appendChild(br);
row.appendChild(input);
row.appendChild(label);
}
function createInput(inputType, inputID, inputName) {
var input = document.createElement("input");
input.setAttribute("type", inputType);
input.setAttribute("id", inputID);
input.setAttribute("name", inputName);
return input;
}
I want to access the textbox (which created dynamically) in .cs.
How to do that ?
The Full Answer :
var $ = $telerik.$;
function onClientFileUploaded(radAsyncUpload, args) {
var $row = $(args.get_row());
var inputName = radAsyncUpload.getID("TextBox");
var inputType = "text";
var inputID = inputName;
var input = createInput(inputType, inputID, inputName);
var label = createLabel(inputID);
$row.append("<br/>");
$row.append(label);
$row.append(input);
}
function createInput(inputType, inputID, inputName) {
var input = '<input type="' + inputType + '" id="' + inputID + '" name="' + inputName + '" />';
return input;
}
function createLabel(forArrt) {
var label = '<label for=' + forArrt + '>info: </label>';
return label;
}
foreach (UploadedFile UF in rada_attach.UploadedFiles)
{
if (UF.GetFieldValue("TextBox") != null)
{
OBJ.File_name = UF.GetFieldValue("TextBox");
}
else
{
OBJ.File_name = UF.GetName();
}
In my opinion documentation is well clear. Check the Description tab on page you refer on. You can access value of dynamic textboxes with code below on postback:
if (rada_attach.UploadedFiles.Count > 0) {
for (var index = 0; index < rada_attach.UploadedFiles.Count; ++index) {
var textBoxValue = rada_attach.UploadedFiles[index].GetFieldValue("TextBox");
}
}
BTW, this scenario is well-dcoumented here: Adding Information to Uploaded Files
You need to check the Request.Form values (that were in the posted form) on postback and perform a check on all the fields that were posted back.
I am guessing that you won't know the name/id of the textbox if it was created on the client-side dynamically? Note that it would be the name of the form field that the Request object in .cs would see.
Only once you have posted back can you access that value in the .cs

Why do I get an "$ is not defined" error?

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 );

Categories