Setup TinyMce editor in C# MVC 4 - Visual Studio 2012 - c#

Always get this error:
get: 0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'tinymce'
By Nuget: PM> Install-Package TinyMCE.MVC.JQuery newest version
Model Class:
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
namespace Familytree.Models {
public class TinyMCEModelJQuery {
[AllowHtml]
[UIHint("tinymce_jquery_full")]
public string Content { get; set; }
}
}
Controller:
using System.Web.Mvc;
namespace Familytree.Controllers {
public class TinyMCESampleJQueryController : Controller {
//
// GET: /TinyMCESampleJQuery/
[ValidateInput(false)]
public ActionResult Index() {
return View();
}
}
}
View:
#model Familytree.Models.TinyMCEModelJQuery
<h2>Index</h2>
#using (Html.BeginForm())
{
<fieldset>
<legend>TinyMCEModel</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Content)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Content)
#Html.ValidationMessageFor(model => model.Content)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
tinymce_jquery_full under Shared folder and Editor Template
#*
Don't forget to reference the JQuery Library here, inside your view or layout.
<script src="#Url.Content("~/Scripts/jquery-x.x.x.min.js")" type="text/javascript"></script>
*#
<script src="#Url.Content("~/Scripts/tinymce/jquery.tinymce.js")" type="text/javascript"></script>
<script type="text/javascript">
(function(){
$(function() {
$('##ViewData.TemplateInfo.GetFullHtmlFieldName(string.Empty)').tinymce({
// Location of TinyMCE script
script_url: '#Url.Content("~/Scripts/tinymce/tiny_mce.js")',
theme: "advanced",
height: "500",
width: "790",
verify_html : false,
plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist,autosave",
// Theme options
theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak,restoredraft,codehighlighting,netadvimage",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
theme_advanced_resizing : false,
// Example content CSS (should be your site CSS)
content_css : "#Url.Content("~/Scripts/tinymce/css/content.css")",
convert_urls : false,
// Drop lists for link/image/media/template dialogs
template_external_list_url : "lists/template_list.js",
external_link_list_url : "lists/link_list.js",
external_image_list_url : "lists/image_list.js",
media_external_list_url : "lists/media_list.js"
});
});
})();
</script>
#Html.TextArea(string.Empty, /* Name suffix */
ViewData.TemplateInfo.FormattedModelValue /* Initial value */
)
Do I change this last line to
#Html.EditorFor(string.Empty, /* Name suffix */
ViewData.TemplateInfo.FormattedModelValue /* Initial value */
)
Using EditorFor in the Index view

Your partial view should be something like this
<script src="#Url.Content("~/Scripts/tinymce/tiny_mce.js")" type="text/javascript"></script>
<script type="text/javascript">
(function () {
tinyMCE.init({
mode: "exact",
elements: "#ViewData.TemplateInfo.GetFullHtmlFieldName(string.Empty)",
theme: "simple",
height: "300",
width: "400",
verify_html: false,
theme_simple_resizing: true,
content_css: "#Url.Content("~/Content/Site.css")",
convert_urls: false
})
})();
</script>
#Html.TextArea(string.Empty, /* Name suffix */
ViewData.TemplateInfo.FormattedModelValue /* Initial value */
)
or change the theme to advanced, anyways when i was doing this i used this https://www.nuget.org/packages/TinyMCE and it was working fine. all you need to do is add [UIHint("tinymce_jquery_full")] before the string definition in your model. i dont see the need for the controller TinyMCESampleJQueryController
Hope this helps

You can try this, Nothing else
In View Model
#Html.TextAreaFor(c => c.ColumnName, new { #class = "tinyEditor", #autocomplete = "off" })
In script
<script type="text/javascript">
tinymce.init({
selector: ".tinyEditor",
theme: "modern",
menubar: false,
width: 400,
height: 100,
plugins: [
"advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker",
"searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
"save table contextmenu directionality emoticons template paste textcolor"
],
content_css: "/Areas/Admin/Content/lang/en/assets/css/style.css",
toolbar: "styleselect | bold italic | bullist numlist outdent indent",
style_formats: [
{ title: 'Bold text', inline: 'b' },
{ title: 'Red text', inline: 'span', styles: { color: '#ff0000' } },
{ title: 'Red header', block: 'h1', styles: { color: '#ff0000' } },
{ title: 'Example 1', inline: 'span', classes: 'example1' },
{ title: 'Example 2', inline: 'span', classes: 'example2' },
{ title: 'Table styles' },
{ title: 'Table row 1', selector: 'tr', classes: 'tablerow1' }
]
});
JS
https://cdnjs.cloudflare.com/ajax/libs/tinymce/5.0.6/jquery.tinymce.min.js
It's working do not write the code any other, just use class name in model and tinymce script

Related

C# MVC ajax call to database with a popup model does not recognize cancel button click

I have a c# application which displays a webgrid populated by a database. When I double click on a grid element, jquery captures the double click, determines the row of the grid, finds the ID column and does an ajax call to pass the ID back to my controller. Ajax is instructed to expect html as the response.
When the controller receives the ID from the view, it reads the record from the database with that ID, populates a list with a set of fields, and passes that list as a parameter to a partial view.
The partial view returns html to the ajax call. The html includes a form where the database fields are displayed in text boxes so the user can update the data. There is a submit button and a cancel button at the bottom of the form.
The is the ajax code:
$("body").on("dblclick", "#WebGrid td", function () {
var row = $(this).closest("tr");
var FirstName = row.find("td").eq(1).text();
var LastName = row.find("td").eq(2).text();
var ID = row.find("td").eq(0).text();
$.ajax({
url: "/Home/Details",
type: "POST",
data: { ID: ID, FirstName: "", LastName: "", EmailAddress: "", EmailType: "" },
dataType: "html",
success: function (result) {
$('#dialog').html(result);
$('#dialog').dialog('open');
},
failure: function (result) {
alert("FAILURE " + result.responseText);
},
error: function (result) {
alert("ERROR " + result.responseText);
}
});
return false;
});
And this is how I define the division that the returned html gets placed into:
<div id="dialog" style="display: none">
</div>
And this is the function that I have:
$(function () {
$("#dialog").dialog({
autoOpen: false,
modal: true,
title: "Update"
});
});
When I run the application, and I double click on a grid item and the partial view gets passed back to the ajax call, the dialog division gets displayed correctly with the data from the database.
The problem is when I click on the Cancel button nothing happens. And I do not get the 'cancel button clicked' message on the console. I have this code to capture the click of the cancel button:
$("#btnCancel").on('click', function (event) {
console.log("cancel button clicked");
$('#dialog').hide;
toastr.warning("Your update has been cancelled");
clear();
display();
});
Any suggestions? Thank you.
edit:
Here is the entire code of the initial View where the grid is rendered:
#model List<CodingChallengeV4.ViewModels.ContactPassData>
#{
ViewBag.Title = "UpdateAllData";
}
#{
Layout = null;
WebGrid grid = new WebGrid(source: Model, canPage: true, canSort: false);
}
<!-- jQuery library -->
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.jquery.com/jquery-migrate-3.0.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js">
</script>
<script src="https://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" />
<!-- Latest compiled JavaScript -->
<!-- add thids links for the error message-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/css/toastr.css" />
<script src="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/js/toastr.js"></script>
<style type="text/css">
.Grid {
border: 1px solid #ccc;
border-collapse: collapse;
}
.Grid th {
background-color: #F7F7F7;
font-weight: bold;
}
.Grid th, .Grid td {
padding: 5px;
width: 150px;
border: 1px solid #ccc;
}
.Grid, .Grid table td {
border: 0px solid #ccc;
}
.Grid th a, .Grid th a:visited {
color: #333;
}
</style>
<h2>Update All Contacts</h2>
#grid.GetHtml(
htmlAttributes: new { #id = "WebGrid", #class = "Grid" },
columns: grid.Columns(
grid.Column(header: "", format:#<text><div class="edit" data-id="#item.passedID" data-propertyname="passedID">#item.passedID</div></text>),
grid.Column(header: "First Name", format:#<text><div class="edit" data-id="#item.passedID" data-propertyname="passedfName">#item.passedfName</div></text>),
grid.Column(header: "Last Name", format:#<text><div class="edit" data-id="#item.passedID" data-propertyname="passedlName">#item.passedlName</div></text>),
grid.Column(header: "eMail Address", format:#<text><div class="edit" data-id="#item.passedID" data-propertyname="passedeMail">#item.passedeMail</div></text>),
grid.Column(header: "eMail Type", format:#<text><div class="edit" data-id="#item.passedID" data-propertyname="passedeMailTypeString">#item.passedeMailTypeString</div></text>)
)
)
<div id="dialog" style="display: none;" >
</div>
<script>
$(function () {
$("#dialog").dialog({
autoOpen: false,
modal: true,
title: "View Details"
});
});
$(document).ready(function () {
$('#toast-container').find('.toast-top-center').removeClass('.toast-top-center');
toastr.options = {
"closeButton": true,
'autoWidth': false,
"debug": false,
"newestOnTop": true,
"progressBar": true,
"positionClass": "toast-center-center",
"preventDuplicates": false,
"onclick": null,
"showDuration": "300",
"hideDuration": "1000",
"timeOut": "3000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
}
$("#btnCancel").on('click', function (event) {
console.log("cancel button was clicked");
$('#dialog').dialog('hide');
toastr.warning("Your update has been cancelled");
clear();
display();
});
$("body").on("dblclick", "#WebGrid td", function () {
var row = $(this).closest("tr");
var FirstName = row.find("td").eq(1).text();
var LastName = row.find("td").eq(2).text();
var ID = row.find("td").eq(0).text();
$.ajax({
url: "/Home/Details",
type: "POST",
data: { ID: ID, FirstName: "", LastName: "", EmailAddress: "", EmailType: "" },
dataType: "html",
success: function (result) {
$('#dialog').html(result);
$('#dialog').dialog('open');
},
failure: function (result) {
alert("FAILURE " + result.responseText);
},
error: function (result) {
alert("ERROR " + result.responseText);
}
});
return false;
});
});
</script>

kendo grid client template input hidden field become editable once click

I'm trying to make a kendo grid column template like this, based on condition show text input and other way round
wrote the following code for this
columns.Bound(p => p.MyColumn).Template(#<text></text>).ClientTemplate(
"# if (myFirstCondion == true) { #" +
"<input type='text' style='width:100%' class='k-textbox' value=#=MyColumn#></input>" +
"# } else { #" +
"<input type='hidden'></input>" +
"# } #"
);
but the problem is when I click hidden column, its become input text field,
how to make this non editable once click hidden field
You could use the column.Editable handler.
e.g.
columns.Bound(p => p.MyColumn).Editable("conditionalEditable").Template(#<text></text>).ClientTemplate(
"# if (myFirstCondion == true) { #" +
"<input type='text' style='width:100%' class='k-textbox' value=#=MyColumn#></input>" +
"# } else { #" +
"<input type='hidden'></input>" +
"# } #"
);
...
<script>
function conditionalEditable(dataItem){
return dataItem.myFirstCondion; // add the same per item condition as in the client template
}
</script>
Let me guess: Your grid is editable right? If so, your grid will take control over the cell's content when editing. You need to customize it, like the example below:
<!DOCTYPE html>
<html>
<head>
<base href="https://demos.telerik.com/kendo-ui/grid/local-data-binding">
<style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style>
<title></title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2021.2.616/styles/kendo.default-v2.min.css" />
<script src="https://kendo.cdn.telerik.com/2021.2.616/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2021.2.616/js/kendo.all.min.js"></script>
</head>
<body>
<script src="../content/shared/js/products.js"></script>
<div id="example">
<div id="grid"></div>
<script>
$(document).ready(function() {
$("#grid").kendoGrid({
dataSource: {
data: products,
schema: {
model: {
fields: {
ProductName: { type: "string" },
UnitPrice: { type: "number" },
UnitsInStock: { type: "number" },
Discontinued: { type: "boolean" },
Test: { type: "string" }
}
}
},
pageSize: 20
},
height: 550,
scrollable: true,
sortable: true,
filterable: true,
editable: true,
pageable: {
input: true,
numeric: false
},
columns: [
"ProductName",
{ field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: "130px" },
{ field: "UnitsInStock", title: "Units In Stock", width: "130px" },
{ field: "Discontinued", width: "130px" },
{ field: "Test", editor: ($td, data) => {
if (data.model.Discontinued) {
let myColumn = 1;
$td.append(`<input type='text' style='width:100%' class='k-textbox' value='${myColumn}'></input>`);
} else {
$td.append("<input type='hidden'></input>");
}
}
}
]
});
});
</script>
</div>
</body>
</html>
Dojo
So inside the editor callback, you can create(or not) your own input depending on any condition you need. You also have the model.

Charts not showing on ASP.NET MVC page

I am pretty new to asp.net so I tried to add a simple bar chart with charts.js to my view but all I get is an empty page.
Controller
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
List<string> iData = new List<string>();
List<string> iData2 = new List<string>();
iData.Add("Sam");
iData2.Add("555");
iData.Add("Alex");
iData2.Add("666");
iData.Add("Michael");
iData2.Add("777");
ViewBag.Value_List = iData2;
ViewBag.Name_List = iData;
return View();
}
}
View:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Charts</title>
<script src="~/Scripts/Chart.min.js"></script>
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
var barChartData =
{
labels: [#Html.Raw(ViewBag.Name_List)],
datasets: [{
label: 'ChartTest',
backgroundColor: [
"#f990a7",
"#aad2ed",
"#9966FF",
"#99e5e5",
"#f7bd83",
],
borderWidth: 2,
data: [#ViewBag.Value_List]
}]
};
window.onload = function () {
var ctx1 = document.getElementById("barcanvas").getContext("2d");
window.myBar = new Chart(ctx1,
{
type: 'bar',
data: barChartData,
options:
{
title:
{
display: true,
text: "ChartTest"
},
responsive: true,
maintainAspectRatio: true
}
});
}
</script>
</head>
<body>
<div style="text-align: center">
<canvas id="barcanvas"></canvas>
</div>
</body>
</html>
I tried to help me with some tutorials but nothing worked for me.
Can someone tell me what I am doing wrong?
Two changes needed:
Serialize the data into JSON in the controller:
using System.Web.Script.Serialization;
var js = new JavaScriptSerializer();
ViewBag.Value_List = js.Serialize( iData2);
ViewBag.Name_List = js.Serialize(iData);
Remove the extra square brackets in the view:
labels: #Html.Raw(ViewBag.Name_List),
data: #Html.Raw(ViewBag.Value_List)
You need to create "drop in" JavaScript to represent the data.
labels: ["555","666","777"] ,
data: ["Sam","Alex","Michael"]

ASP MVC Razor View doesn't want to show #Html.TextBoxFor value from the model

my razor view is accepting a model ... and I have this code in it ..
#{
var my_value = "wth";
if (Model.app != null)
{ my_value = Model.app.name; }
}
#Html.TextBoxFor(a => a.app.name, new { #Value = my_value })
shows 'wth' when the model isn't null ... did some debugging to see if my_value is set properly ... hmmm
Edit:
Thank you for the comments.
A bit new to ASP MVC. Some background to what I am trying to do:
I have a main view, Main.cshtml, which shows records. Each record can be edited by clicking glyphicon.
JS code grabs the record_id and makes Ajax call to Application Controller / editApp action.
I have a partial, _EditApplication.cshtml, within Main.cshtml, to show my tabbed jQuery UI dialog. And also uses _AddAppForm.cshtml partial that takes a Model to be shown in the data fields.
.... I think this is where my problem is (among others lol)... I am calling the partial (_EditApplication.cshtml) in the main view ... and I am returning the same partial in my Controller Action with an associated model.
Code:
Main.cshmtl
#{ AppDBServer this_ads = new AppDBServer(); }
#Html.Partial("_EditApplication", this_ads)
<div id=#app.app_id.ToString() class="glyphicon glyphicon-pencil btn_edit_app" aria-hidden="true" style="color:blue; cursor:pointer"></div>
JS code in Main.cshtml
$('.btn_edit_app').click(function () {
var app_to_edit = $(this).attr('id');
$.ajax({
url: '/Application/editApp',
contentType: 'application/html; charset=utf-8',
data: { app_id: app_to_edit},
type: 'GET',
dataType: 'html',
success: function (result) {},
});
$('#edit_tabs').tabs({ active: 0 });
$('#edit_dialog').dialog({ width: 700, height: 400 });
});
_EditApplication.cshtml - Partial
#using NameSpace.Models
#model AppDBServer
<div id="edit_dialog" title="Edit Application" style="display: none">
#using (Html.BeginForm("saveApps", "Application", new { isNew = false })) {
<div id="edit_tabs">
<ul><li>Application</li></ul>
#Html.Partial("_AddAppForm", #Model)
</div>
}
</div>
Application Controller - Action: editApp
namespace SHS_Connect.Controllers
{
public class ApplicationController : Controller
{
public ActionResult editApp(int app_id)
{
AppDBServer ads = new AppDBServer();
ads = findADS(app_id);
return PartialView("_EditApplication", ads);
}
}
}
_AddAppForm.cshmtl - Partial used in _EditApplication.cshtml
#using NameSpace.Models
#model AppDBServer
<div id="application">
<div class="form-group">
#Html.LabelFor(a => a.app.name)
#{
var my_value = "wth";
if (Model.app != null)
{ my_value = Model.app.name; }
}
#Html.TextBoxFor(a => a.app.name, new { #Value = my_value })
</div>
</div>
So, yea, I figure it out ... in case someone gets stuck like this ... changes to make:
Main.cshmtl:
adding the partial here doesn't work, have to replace it with a div tag w/id that will contain the partial ...
<div id="div_editapp_dialog"></div>
JS Code in Main.cshtml:
The success function should populate the div and get the tabs / dialog going.
success: function (result) {
$('#div_editapp_dialog').html(result);
$('#edit_tabs').tabs({ active: 0 });
$('#edit_dialog').dialog({ width: 700, height: 400 });
}
No change to _EditApplication.cshtml and the Controller.
Clean up _AddAppForm.cshmtl ...
<div class="form-group">
#Html.LabelFor(a => a.app.name)
#Html.TextBoxFor(a => a.app.name)
</div>

JQuery Datatables Server Side Processing Bug

I am using the latest Nuget Datatables Package.
From the Nuget Package I am using the following two scripts
<link rel="stylesheet" href="/Content/DataTables/css/jquery.dataTables.min.css" type="text/css" />
<script src="/Scripts/DataTables/jquery.dataTables.min.js"></script>
The following is my client table, it contains 28 records in the database and I am trying to display 10 records
Below is my cshtml
<script>
$(document).ready(function () {
$('#clientTable').DataTable({
"order": [[1, "asc"]],
"serverSide": true,
"processing": true,
"paging": true,
"bLengthChange": false,
"iDisplayLength": "10",
"ajax": {
"url": "/Client/GetAll",
"type": "POST",
"dataType": "json"
},
"columns":
[
{
data: "ID", title: "", render: function (o) {
var template = "<div class=\"btn-group\"><button type=\"button\" class=\"btn btn-primary dropdown-toggle\" data-toggle=\"dropdown\"> Options <span class=\"caret\"></span></button>"
+ "<ul class=\"dropdown-menu\" role=\"menu\">"
+ "<li style=\"display: #InspectionMethods.ValidateDisplayAccessRights(AccessRights.ViewInspections)\">"
+ "Edit"
+ "</li>"
+ "<li class=\"divider\"></li>"
+ "<li style=\"display: #InspectionMethods.ValidateDisplayAccessRights(AccessRights.ManageEmployees)\">"
+ " View Inspections "
+ "</li></ul></div>";
return template;
}
},
{ data: "Name", title: "Company" },
{ data: "CellNumber", title: "Contact Number" }
]
});
});
</script>
<div class="row">
<div class="col-md-12">
<div class="portlet">
<div class="portlet-header">
<h3 class="pull-right">
<a style="display: #InspectionMethods.ValidateDisplayAccessRights(AccessRights.ManageEmployees)" href="#Url.Action("CreateClient")" class="btn btn-success pull-right">New Client</a>
</h3>
</div> <!-- /.portlet-header -->
<div class="portlet-content">
<table id="clientTable" class="table table-striped table-bordered table-hover table-highlight"></table>
</div> <!-- /.portlet-content -->
</div> <!-- /.portlet -->
</div> <!-- /.col -->
</div> <!-- /.row -->
Here is my server side
[HttpPost]
public ActionResult GetAll(JQDTParams model)
{
using (var context = new DatabaseContext())
{
var clients = context.Clients.Where(model).ToList();
var result = new
{
model.sEcho,
model.draw,
recordsFiltered = context.Clients.Count(model), // 28
recordsTotal = context.Clients.Count(), // 28
data = clients // 10 Items in the list
};
return Json(result, JsonRequestBehavior.AllowGet);
}
}
The result I am getting looks like this
EDIT 1:)
Pages now display.
Pressing on Page 1, 2, or 3 it works and displays the correct data.
Now if I go to Page one and Press "Next" I get the result above where the text then says Showing 0,101 to 28 of 28 entries and if I press "Next" again to go to page three it doesn't do anything
Found the problem
It seems that jquery.Datatables handled the "iDisplayLength" as a string instead of an int, simple change
$(document).ready(function () {
$('#clientTable').DataTable({
"order": [[1, "asc"]],
"serverSide": true,
"processing": true,
"paging": true,
"bLengthChange": false,
"iDisplayLength": 10, //Here was the problem

Categories