I'm trying to specify headers and footers in a PDF generated by Rotativa library. As the author answered here it should be possible using CSS (described here). However, I'm not able to do this.
I have a stylesheet loaded in the meta tag:
<link href="print.css" rel="stylesheet" type="text/css" media="print" />
And in the stylesheet at the bottom:
#page {
#top-left {
content: "TOP SECRET";
color: red
}
#bottom-right {
content: counter(page);
font-style: italic
}
}
And then generating PDF by:
public ActionResult ShowPdf()
{
var model = new Model();
return new ViewAsPdf("view.cshtml", model)
{
FileName = "Report.pdf",
CustomSwitches = "--print-media-type"
};
}
And then nothing appears in the header and footer of the PDF. Any ideas?
I've found a documentation of wkhtmltopdf (or a better archived version) and it is described there how to manage headers and footers.
Basically you can just add --header-center "text" (or similar switches) to the argument list and that's all.
So using it with Rotativa it would be:
public ActionResult ShowPdf()
{
var model = new Model();
return new ViewAsPdf("view.cshtml", model)
{
FileName = "Report.pdf",
CustomSwitches = "--print-media-type --header-center \"text\""
};
}
(I don't know if --print-media-type is necessary.)
If you wanted to display a View instead of text in the header/footer then you can do so like this:
public ActionResult ViewPDF()
{
string customSwitches = string.Format("--print-media-type --allow {0} --footer-html {0} --footer-spacing -10",
Url.Action("Footer", "Document", new { area = ""}, "https"));
return new ViewAsPdf("MyPDF.cshtml", model)
{
FileName = "MyPDF.pdf",
CustomSwitches = customSwitches
};
}
[AllowAnonymous]
public ActionResult Footer()
{
return View();
}
Don't forget to add the [AllowAnonymous] attribute on the Footer action otherwise Rotatina can't get access to the path.
Here is how I did it (in full):
public ActionResult PrintPDF(int? selectedSiteRotaId, int selectedSiteId)
{
string footer = "--footer-center \"Printed on: " + DateTime.Now.Date.ToString("MM/dd/yyyy") + " Page: [page]/[toPage]\"" + " --footer-line --footer-font-size \"9\" --footer-spacing 6 --footer-font-name \"calibri light\"";
return new ActionAsPdf("RenderPDF", new { selectedSiteRotaId = selectedSiteRotaId, selectedSiteId = 7 })
{
FileName = "PDF_Output.pdf",
PageOrientation = Orientation.Landscape,
MinimumFontSize = 10,
//PageMargins = new Margins(5,5,5,5),
PageSize = Size.A3,
CustomSwitches = footer
};
//var pdfResult = new ActionAsPdf("RenderPDF", new { selectedSiteRotaId = selectedSiteRotaId, selectedSiteId = 7 })
//{
// FileName = "PDF_Output.pdf",
// PageOrientation = Orientation.Landscape,
// MinimumFontSize = 10
//};
//var binary = pdfResult.BuildPdf(this.ControllerContext);
//return File(binary, "application/pdf");
}
public ActionResult RenderPDF(int? selectedSiteRotaId, int selectedSiteId)
{
return RedirectToAction("Index", "PrintPDF", new { selectedSiteRotaId = selectedSiteRotaId, selectedSiteId = 7 });
}
string customSwitches = string.Format("--header-spacing \"0\" --footer-spacing \"0\" --footer-html {0} ", Url.Action("Footer", "Invoice", new { }, "http"));
return new ViewAsPdf(saleInvoiceVm)
{
PageOrientation = Orientation.Portrait,
PageSize = Rotativa.AspNetCore.Options.Size.A4,
PageMargins = { Left = 5, Bottom = 25, Right = 7, Top = 10 },
CustomSwitches = customSwitches,
};
try it it will work 100 %
return new ViewAsPdf("MyPDF.cshtml", model)
{
FileName = "MyPDF.pdf",
CustomSwitches = customSwitches
};
}
Related
I want to print my table in the infinite category system to my cshtml screen with tagbuilder. writes some of it. some of it is not written. please help me.
c# codes:
public IActionResult Index()
{
var tb = new TagBuilder("ul");
using (SqlDbContext vt = new SqlDbContext())
{
var Kategori = from i in vt.urunKategorileri
where i.urunKategorileriUstId == 0
select i;
foreach (urunKategorileri anamenu in Kategori)
{
tb.InnerHtml.AppendHtml("<li><a href='#'>" + anamenu.urunKategorileriKategoriAdi + "</a>"+ Altkategori(anamenu.urunKategorileriId) + "</li>");
}
}
return View(tb);
}
private TagBuilder Altkategori(int id)
{
TagBuilder eb = new TagBuilder("ul");
using (SqlDbContext a = new SqlDbContext())
{
var say = (from i in a.urunKategorileri
where i.urunKategorileriUstId == id
select i).Count();
if (say > 0)
{
TagBuilder ab = new TagBuilder("<ul>");
var altKat = from i in a.urunKategorileri
where i.urunKategorileriUstId == id
select i;
foreach (urunKategorileri altkategori in altKat)
{
ab.InnerHtml.AppendHtml("<li><a href='#'>" + altkategori.urunKategorileriKategoriAdi + "</a>"+ Altkategori(altkategori.urunKategorileriId)+ "</li>");
}
return ab;
}
}
return eb;
}
cshtml codes:
#model TagBuilder
#{
ViewData["Title"] = "Home Page";
}
#Model
screenshot:
console output:
In the console, the sub-categories should normally be listed in the section that says "Microsoft.AspNetCore.Mvc.Rendering.TagBuilder" inside the li tag. but it's not working.
You need to convert TagBuilder.InnerHtml to string,if you want to append it to html:
public IActionResult Index()
{
var tb = new TagBuilder("ul");
using (SqlDbContext vt = new SqlDbContext())
{
var Kategori = from i in vt.urunKategorileri
where i.urunKategorileriUstId == 0
select i;
foreach (urunKategorileri anamenu in Kategori)
{
string html = "";
using (var writer = new System.IO.StringWriter())
{
Altkategori(anamenu.urunKategorileriId).InnerHtml.WriteTo(writer, HtmlEncoder.Default);
html = writer.ToString();
}
tb.InnerHtml.AppendHtml("<li><a href='#'>" + anamenu.urunKategorileriKategoriAdi + "</a>" + html + "</li>");
}
}
return View(tb);
}
Creating a PDF document from the stream of a HTTP request.
public class HomeController : Controller {
public HomeController() {
converter = new HtmlToPdf();
InitializeConverter();
}
public void Index() {
ConvertHtmlToPdf(new Uri("http://localhost:52328/CertificateOfOrigin?noCertificate=2691"));
}
public void ConvertHtmlToPdf(Uri toConvert) {
if(toConvert == null) throw new ArgumentNullException(nameof(toConvert));
using(var stream =new MemoryStream()) {
var doc = converter.ConvertUrl(toConvert.AbsoluteUri);
// The doc.AddTemplate returns a PdfTemplate and should be assigned to doc.Footer
doc.Footer = doc.AddTemplate(doc.Pages[0].ClientRectangle.Width, 100);
var pageNumbering = new PdfTextElement(20, 50, "Page {page_number} of {total_pages}", doc.Fonts[0], Color.Black);
// Once template defined, I add it to the doc Footer. But...
doc.Footer.Add(pageNumbering); // Throws a NullPointerException?
doc.Footer = template;
doc.Save(stream);
doc.Close();
using(var ms = new MemoryStream(stream.ToArray())) {
Response.AddHeader("content-disposition", "filename=certificate-of-origin.pdf");
Response.ContentType = "application/pdf";
ms.CopyTo(Response.OutputStream);
Response.End();
Response.Close();
}
}
}
private void InitializeConverter() {
converter.Options.MarginBottom = 0;
converter.Options.MarginLeft = 0;
converter.Options.MarginRight = 0;
converter.Options.MarginTop = 0;
converter.Options.PdfPageSize = PdfPageSize.Letter;
}
private readonly HtmlToPdf converter;
}
I put a breakpoint and quick watched the return of doc.AddTemplate method call and it returns an actual PdfTemplate no problem!
Other than that, everything works fine. Document is generated no problem, except when I uncomment the page numbering because the doc.Footer remains null despite its assignment.
Could it be a bug? Idk.
You need to either set the header/footer content before the conversion, like here:
https://selectpdf.com/demo-mvc/HtmlToPdfHeadersAndFooters
using System;
using System.Web.Mvc;
namespace SelectPdf.Samples.Controllers
{
public class HtmlToPdfHeadersAndFootersController : Controller
{
// GET: HtmlToPdfHeadersAndFooters
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult SubmitAction(FormCollection collection)
{
// get parameters
string headerUrl = Server.MapPath("~/files/header.html");
string footerUrl = Server.MapPath("~/files/footer.html");
bool showHeaderOnFirstPage = collection["ChkHeaderFirstPage"] == "on";
bool showHeaderOnOddPages = collection["ChkHeaderOddPages"] == "on";
bool showHeaderOnEvenPages = collection["ChkHeaderEvenPages"] == "on";
int headerHeight = 50;
try
{
headerHeight = Convert.ToInt32(collection["TxtHeaderHeight"]);
}
catch { }
bool showFooterOnFirstPage = collection["ChkFooterFirstPage"] == "on";
bool showFooterOnOddPages = collection["ChkFooterOddPages"] == "on";
bool showFooterOnEvenPages = collection["ChkFooterEvenPages"] == "on";
int footerHeight = 50;
try
{
footerHeight = Convert.ToInt32(collection["TxtFooterHeight"]);
}
catch { }
// instantiate a html to pdf converter object
HtmlToPdf converter = new HtmlToPdf();
// header settings
converter.Options.DisplayHeader = showHeaderOnFirstPage ||
showHeaderOnOddPages || showHeaderOnEvenPages;
converter.Header.DisplayOnFirstPage = showHeaderOnFirstPage;
converter.Header.DisplayOnOddPages = showHeaderOnOddPages;
converter.Header.DisplayOnEvenPages = showHeaderOnEvenPages;
converter.Header.Height = headerHeight;
PdfHtmlSection headerHtml = new PdfHtmlSection(headerUrl);
headerHtml.AutoFitHeight = HtmlToPdfPageFitMode.AutoFit;
converter.Header.Add(headerHtml);
// footer settings
converter.Options.DisplayFooter = showFooterOnFirstPage ||
showFooterOnOddPages || showFooterOnEvenPages;
converter.Footer.DisplayOnFirstPage = showFooterOnFirstPage;
converter.Footer.DisplayOnOddPages = showFooterOnOddPages;
converter.Footer.DisplayOnEvenPages = showFooterOnEvenPages;
converter.Footer.Height = footerHeight;
PdfHtmlSection footerHtml = new PdfHtmlSection(footerUrl);
footerHtml.AutoFitHeight = HtmlToPdfPageFitMode.AutoFit;
converter.Footer.Add(footerHtml);
// add page numbering element to the footer
if (collection["ChkPageNumbering"] == "on")
{
// page numbers can be added using a PdfTextSection object
PdfTextSection text = new PdfTextSection(0, 10,
"Page: {page_number} of {total_pages} ",
new System.Drawing.Font("Arial", 8));
text.HorizontalAlign = PdfTextHorizontalAlign.Right;
converter.Footer.Add(text);
}
// create a new pdf document converting an url
PdfDocument doc = converter.ConvertUrl(collection["TxtUrl"]);
// custom header on page 3
if (doc.Pages.Count >= 3)
{
PdfPage page = doc.Pages[2];
PdfTemplate customHeader = doc.AddTemplate(
page.PageSize.Width, headerHeight);
PdfHtmlElement customHtml = new PdfHtmlElement(
"<div><b>This is the custom header that will " +
"appear only on page 3!</b></div>",
string.Empty);
customHeader.Add(customHtml);
page.CustomHeader = customHeader;
}
// save pdf document
byte[] pdf = doc.Save();
// close pdf document
doc.Close();
// return resulted pdf document
FileResult fileResult = new FileContentResult(pdf, "application/pdf");
fileResult.FileDownloadName = "Document.pdf";
return fileResult;
}
}
}
Or use this approach, to add headers/footers to an already generated pdf:
https://selectpdf.com/demo-mvc/ExistingPdfHeadersAndFooters
using System.Web.Mvc;
using System.Drawing;
namespace SelectPdf.Samples.Controllers
{
public class ExistingPdfHeadersAndFootersController : Controller
{
// GET: ExistingPdfHeadersAndFooters
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult SubmitAction(FormCollection collection)
{
// the test file
string filePdf = Server.MapPath("~/files/selectpdf.pdf");
string imgFile = Server.MapPath("~/files/logo.png");
// resize the content
PdfResizeManager resizer = new PdfResizeManager();
resizer.Load(filePdf);
// add extra top and bottom margins
resizer.PageMargins = new PdfMargins(0, 0, 90, 40);
// add the header and footer to the existing (now resized pdf document)
PdfDocument doc = resizer.GetDocument();
// header template (90 points in height) with image element
PdfTemplate header = doc.AddTemplate(doc.Pages[0].ClientRectangle.Width, 90);
PdfImageElement img1 = new PdfImageElement(10, 10, imgFile);
header.Add(img1);
// footer template (40 points in height) with text element
PdfTemplate footer = doc.AddTemplate(new RectangleF(0,
doc.Pages[0].ClientRectangle.Height - 40,
doc.Pages[0].ClientRectangle.Width, 40));
// create a new pdf font
PdfFont font2 = doc.AddFont(PdfStandardFont.Helvetica);
font2.Size = 12;
PdfTextElement text1 = new PdfTextElement(10, 10,
"Generated by SelectPdf. Page number {page_number} of {total_pages}.",
font2);
text1.ForeColor = System.Drawing.Color.Blue;
footer.Add(text1);
// save pdf document
byte[] pdf = doc.Save();
// close pdf document
resizer.Close();
// return resulted pdf document
FileResult fileResult = new FileContentResult(pdf, "application/pdf");
fileResult.FileDownloadName = "Document.pdf";
return fileResult;
}
}
}
The best approach is the first, so try to move your footer setting before the conversion.
I am creating an internal site for my company, my landing page consists of tiles that are a mix of required and optional tiles. The list of tiles and their respective order are save in a cookie as a JSON string. I build the cookie just fine, i can update it whenever the order changes without a problem. I issue is when i have them click on the remove button on the optional tile. It will not remove it from the cookie.
Here is the code in the partial for the ajax request:
#Ajax.ActionLink(" ", "RemoveTile", "Home", new { id = "_EventsTile" }, new AjaxOptions { OnSuccess= "$(this).closest('.tilePartial').remove(); location.reload();" }, new { #class = "fas fa-clickable fa-window-close removeTile", #style = "color:red; font-size:1.5em; padding-top:1%" })
Here is the code of the action in the controller:
private void UpdateCookie(object obj, string cookieName, int expiredays = 30)
{
HttpCookie cookie = new HttpCookie(cookieName);
cookie.Value = JsonConvert.SerializeObject(obj);
cookie.Expires = DateTime.Now.AddDays(expiredays);
Response.SetCookie(cookie);
Response.Cookies.Add(cookie);
}
public void RemoveTile(string id)
{
List<TileInfo> newCookie = new List<TileInfo>();
var cookieInfo = JsonConvert.DeserializeObject<List<TileInfo>>(Request.Cookies["TilePreferences"].Value);
var removed = cookieInfo.FirstOrDefault(f => f.PartialName == id);
cookieInfo.Remove(removed);
//newCookie = cookieInfo;
UpdateCookie(cookieInfo, "TilePreferences", 90);
Response.StatusCode = 200;
}
and the default value and what is is "supposed" to look like when it is done:
Before:
[
{"PartialName":"_BulletinBoardTile","TileOrder":0},
{"PartialName":"_TimeCardTile","TileOrder":1},
{"PartialName":"_FeedbackTile","TileOrder":2},
{"PartialName":"_CouncilTile","TileOrder":3},
{"PartialName":"_EventsTile","TileOrder":4}
]
After(intention):
[
{"PartialName":"_BulletinBoardTile","TileOrder":0},
{"PartialName":"_TimeCardTile","TileOrder":1},
{"PartialName":"_FeedbackTile","TileOrder":2},
{"PartialName":"_CouncilTile","TileOrder":3}
}
any help is appreciated.
This code for updating the order in the file works with no issues:
public void UpdateTileOrder(string jsonString)
{
List<string> TileList = JsonConvert.DeserializeObject<List<string>>(jsonString);
var cookieInfo = new List<TileInfo>();
var i = 0;
foreach (var item in TileList)
{
if (!string.IsNullOrWhiteSpace(item))
{
var tile = new TileInfo
{
PartialName = item,
TileOrder = i
};
cookieInfo.Add(tile);
i++;
}
}
UpdateCookie(cookieInfo, "TilePreferences", 90);
}
Well im working with Xamarin and I have a WebAPI using Entity Framework. I can already send the images from phone to the webservice but I want to create the records on the database with all the relationships correctly, so basically I have 3 tables to work, as below:
Image
OccurenceImage
Occurence
Model Diagram
In my WebAPI I have two controllers, one to handle the image uploads and another to handle the Occurences. I tried to set a custom ID when I create the record of OccurenceImage but it doesn't work.
ImageUploadController.cs
[HttpPost]
public HttpResponseMessage UploadImage(string imageName)
{
var result = new HttpResponseMessage(HttpStatusCode.OK);
if (Request.Content.IsMimeMultipartContent())
{
Request.Content.LoadIntoBufferAsync().Wait();
Request.Content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider()).ContinueWith((task) =>
{
MultipartMemoryStreamProvider provider = task.Result;
foreach (HttpContent content in provider.Contents)
{
Stream stream = content.ReadAsStreamAsync().Result;
Image image = Image.FromStream(stream);
var testName = content.Headers.ContentDisposition.Name;
String filePath = HostingEnvironment.MapPath("~/Images/");
string nameImg = imageName + Guid.NewGuid();
String fullPath = Path.Combine(filePath, nameImg + ".jpg");
image.Save(fullPath);
AddImageToDb(nameImg);
}
});
return result;
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
}
}
private void AddImageToDb(string imageName)
{
VisitDatabase.Image image = new VisitDatabase.Image()
{
urlImage = imageName + ".jpg"
};
OccurenceImage occurenceImage = new OccurenceImage()
{
idOccurence = 18,
Image = image,
};
db.Image.Add(image);
db.OccurenceImage.Add(occurenceImage);
db.SaveChanges();
}
OccurenceController.cs
[ResponseType(typeof(ActiveCitizen))]
public IHttpActionResult PostOccurence(ActiveCitizen json)
{
Citizen citizen;
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
ActiveCitizen activeCitizen = json;
var query = (from c in db.Citizen
where c.ccbi == activeCitizen.NumDocument
select c.idCitizen).SingleOrDefault();
Address address = new Address()
{
lat = 12,
lon = 12,
street = "Rua do Santuario",
postalCode = "4490-554",
locality = "Barcelos"
};
OccurenceType occurenceType = new OccurenceType()
{
title = activeCitizen.Description,
};
if (query == 0)
{
citizen = new Citizen()
{
ccbi = activeCitizen.NumDocument,
nif = activeCitizen.NIF,
Contact = new Contact()
{
name = activeCitizen.Name,
email = activeCitizen.Email,
phone = activeCitizen.Phone
},
Address = address
};
}
else
{
citizen = db.Citizen.Find(query);
}
Occurence occurence = new Occurence()
{
solved = 0,
occurenceDateTime = new DateTime(2017, 5, 23),
Address = address,
OccurenceType = occurenceType,
Citizen = citizen
};
db.Address.Add(address);
db.OccurenceType.Add(occurenceType);
if (query == 0)
{
db.Contact.Add(citizen.Contact);
db.Citizen.Add(citizen);
}
db.Occurence.Add(occurence);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = occurence.idOccurence }, activeCitizen);
}
Thanks in advance!
The code above is correct, seems like the problem was on the table OccurenceImage the field idOccurenceImage Identity Specification was disabled, just needed to enable and worked like a charm. I hope this helps another people with this kind of newbie problems!
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 );