how to customize details with assert error like adding html table in details using pytest-html? - pytest-html

I try this code:
assert 1=2, "<table>....</table>"
table not showing in details, but strings in the details
how to show html tag with assert error message

i assert two file with difflib and show the message with htmlcontent
self = <test_assert.TestAssert object at 0x00000178F8534748>
def test_assert_match(self):
# with open('c1.json', 'w') as f1:
# json.dump(content1,f1, indent =4, sort_keys = True, separators = (',',':'))
content1 = self.readfile(os.path.join(curr,'1.json'))
content2 = self.readfile(os.path.join(curr,'2.json'))
> MyAssert.assertMatch(content1, content2, True)
Testcases\test_assert.py:34:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
expect = ['{', ' "a": "123"', '}'], actual = ['{', ' "a": "123",', ' "b": "22"', '}'], isHtml = True
#staticmethod
def assertMatch(expect, actual, isHtml = False):
msg = ''
if isHtml:
d = difflib.HtmlDiff()
msg = d.make_file(expect,actual)
with open('diff.html','w') as f:
f.write(msg)
else:
d = difflib.Differ()
diff = d.compare(expect,actual)
msg = "\n".join(list(diff))
> assert expect == actual, msg
E AssertionError:
E <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
E "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
E
E <html>
E
E <head>
E <meta http-equiv="Content-Type"
E content="text/html; charset=utf-8" />
E <title></title>
E <style type="text/css">
E table.diff {font-family:Courier; border:medium;}
E .diff_header {background-color:#e0e0e0}
E td.diff_header {text-align:right}
E .diff_next {background-color:#c0c0c0}
E .diff_add {background-color:#aaffaa}
E .diff_chg {background-color:#ffff77}
E .diff_sub {background-color:#ffaaaa}
E </style>
E </head>
E
E <body>
E
E <table class="diff" id="difflib_chg_to0__top"
E cellspacing="0" cellpadding="0" rules="groups" >
E <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
E <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
E
E <tbody>
E <tr><td class="diff_next" id="difflib_chg_to0__0">f</td><td class="diff_header" id="from0_1">1</td><td nowrap="nowrap">{</td><td class="diff_next">f</td><td class="diff_header" id="to0_1">1</td><td nowrap="nowrap">{</td></tr>
E <tr><td class="diff_next">t</td><td class="diff_header" id="from0_2">2</td><td nowrap="nowrap"> "a": "123"</td><td class="diff_next">t</td><td class="diff_header" id="to0_2">2</td><td nowrap="nowrap"> "a": "123"<span class="diff_add">,</span></td></tr>
E <tr><td class="diff_next"></td><td class="diff_header"></td><td nowrap="nowrap"></td><td class="diff_next"></td><td class="diff_header" id="to0_3">3</td><td nowrap="nowrap"><span class="diff_add"> "b": "22"</span></td></tr>
E <tr><td class="diff_next"></td><td class="diff_header" id="from0_3">3</td><td nowrap="nowrap">}</td><td class="diff_next"></td><td class="diff_header" id="to0_4">4</td><td nowrap="nowrap">}</td></tr>
E </tbody>
E </table>
E <table class="diff" summary="Legends">
E <tr> <th colspan="2"> Legends </th> </tr>
E <tr> <td> <table border="" summary="Colors">
E <tr><th> Colors </th> </tr>
E <tr><td class="diff_add"> Added </td></tr>
E <tr><td class="diff_chg">Changed</td> </tr>
E <tr><td class="diff_sub">Deleted</td> </tr>
E </table></td>
E <td> <table border="" summary="Links">
E <tr><th colspan="2"> Links </th> </tr>
E <tr><td>(f)irst change</td> </tr>
E <tr><td>(n)ext change</td> </tr>
E <tr><td>(t)op</td> </tr>
E </table></td> </tr>
E </table>
E </body>
E
E </html>
Testcases\myAssert.py:50: AssertionError
i want to show the html in the details not strings..

Related

Update SearchPane filter values after filter table using dataTables and SearchPane plugin

I'm testing a plugin for dataTables called SearchPane, it works fine, but when i filter the table using the pane, the values keep stuck, not reflecting the values from the filtered table.
What i need is: after click on some value from the searchPane filter, the filter update values based on values of (filtered) updated table.
The documentation says something about it but not explain how apply it.
searchPane Documentation
The documentation have this information:
API - When the data in the table is updated, you'll want the search
panes to reflect this updated data - which can be done with the
searchPanes.rebuild() method - e.g.:
var table = $('#example').DataTable( {
searchPane: true
} );
table.row.add( ... ).draw();
table.searchPanes.rebuild();
but i don't know how to apply this in a working example.
my code:
$('#example').DataTable( {
searchPane: true
} )
<link href="https://cdn.datatables.net/1.10.11/css/jquery.dataTables.min.css" rel="stylesheet"/>
<link href="https://cdn.datatables.net/plug-ins/preview/searchPane/dataTables.searchPane.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/plug-ins/preview/searchPane/dataTables.searchPane.min.js"></script>
<div class="container">
<table cellpadding="0" cellspacing="0" border="0" class="dataTable" id="example">
<thead>
<tr>
<th>Rendering engine</th>
<th>Browser</th>
<th>Platform(s)</th>
<th>Engine version</th>
<th>CSS grade</th>
</tr>
</thead>
<tbody>
<tr>
<td>Trident</td>
<td>Internet
Explorer 4.0</td>
<td>Win 95+</td>
<td> 4</td>
<td>X</td>
</tr>
<tr>
<td>Trident</td>
<td>Internet
Explorer 5.0</td>
<td>Win 95+</td>
<td>5</td>
<td>C</td>
</tr>
<tr>
<td>Trident</td>
<td>Internet
Explorer 5.5</td>
<td>Win 95+</td>
<td>5.5</td>
<td>A</td>
</tr>
<tr>
<td>Trident</td>
<td>Internet
Explorer 6</td>
<td>Win 98+</td>
<td>6</td>
<td>A</td>
</tr>
<tr>
<td>Trident</td>
<td>Internet Explorer 7</td>
<td>Win XP SP2+</td>
<td>7</td>
<td>A</td>
</tr>
<tr>
<td>Trident</td>
<td>AOL browser (AOL desktop)</td>
<td>Win XP</td>
<td>6</td>
<td>A</td>
</tr>
<tr>
<td>Gecko</td>
<td>Firefox 1.0</td>
<td>Win 98+ / OSX.2+</td>
<td>1.7</td>
<td>A</td>
</tr>
<tr>
<td>Gecko</td>
<td>Firefox 1.5</td>
<td>Win 98+ / OSX.2+</td>
<td>1.8</td>
<td>A</td>
</tr>
<tr>
<td>Gecko</td>
<td>Firefox 2.0</td>
<td>Win 98+ / OSX.2+</td>
<td>1.8</td>
<td>A</td>
</tr>
<tr>
<td>Gecko</td>
<td>Firefox 3.0</td>
<td>Win 2k+ / OSX.3+</td>
<td>1.9</td>
<td>A</td>
</tr>
<tr>
<td>Gecko</td>
<td>Camino 1.0</td>
<td>OSX.2+</td>
<td>1.8</td>
<td>A</td>
</tr>
<tr>
<td>Gecko</td>
<td>Camino 1.5</td>
<td>OSX.3+</td>
<td>1.8</td>
<td>A</td>
</tr>
<tr>
<td>Gecko</td>
<td>Netscape 7.2</td>
<td>Win 95+ / Mac OS 8.6-9.2</td>
<td>1.7</td>
<td>A</td>
</tr>
<tr>
<td>Gecko</td>
<td>Netscape Browser 8</td>
<td>Win 98SE+</td>
<td>1.7</td>
<td>A</td>
</tr>
<tr>
<td>Gecko</td>
<td>Netscape Navigator 9</td>
<td>Win 98+ / OSX.2+</td>
<td>1.8</td>
<td>A</td>
</tr>
<tr>
<td>Gecko</td>
<td>Mozilla 1.0</td>
<td>Win 95+ / OSX.1+</td>
<td>1</td>
<td>A</td>
</tr>
<tr>
<td>Gecko</td>
<td>Mozilla 1.1</td>
<td>Win 95+ / OSX.1+</td>
<td>1.1</td>
<td>A</td>
</tr>
<tr>
<td>Gecko</td>
<td>Mozilla 1.2</td>
<td>Win 95+ / OSX.1+</td>
<td>1.2</td>
<td>A</td>
</tr>
<tr>
<td>Gecko</td>
<td>Mozilla 1.3</td>
<td>Win 95+ / OSX.1+</td>
<td>1.3</td>
<td>A</td>
</tr>
<tr>
<td>Gecko</td>
<td>Mozilla 1.4</td>
<td>Win 95+ / OSX.1+</td>
<td>1.4</td>
<td>A</td>
</tr>
<tr>
<td>Gecko</td>
<td>Mozilla 1.5</td>
<td>Win 95+ / OSX.1+</td>
<td>1.5</td>
<td>A</td>
</tr>
<tr>
<td>Gecko</td>
<td>Mozilla 1.6</td>
<td>Win 95+ / OSX.1+</td>
<td>1.6</td>
<td>A</td>
</tr>
<tr>
<td>Gecko</td>
<td>Mozilla 1.7</td>
<td>Win 98+ / OSX.1+</td>
<td>1.7</td>
<td>A</td>
</tr>
<tr>
<td>Gecko</td>
<td>Mozilla 1.8</td>
<td>Win 98+ / OSX.1+</td>
<td>1.8</td>
<td>A</td>
</tr>
<tr>
<td>Gecko</td>
<td>Seamonkey 1.1</td>
<td>Win 98+ / OSX.2+</td>
<td>1.8</td>
<td>A</td>
</tr>
<tr>
<td>Gecko</td>
<td>Epiphany 2.20</td>
<td>Gnome</td>
<td>1.8</td>
<td>A</td>
</tr>
<tr>
<td>Webkit</td>
<td>Safari 1.2</td>
<td>OSX.3</td>
<td>125.5</td>
<td>A</td>
</tr>
<tr>
<td>Webkit</td>
<td>Safari 1.3</td>
<td>OSX.3</td>
<td>312.8</td>
<td>A</td>
</tr>
<tr>
<td>Webkit</td>
<td>Safari 2.0</td>
<td>OSX.4+</td>
<td>419.3</td>
<td>A</td>
</tr>
<tr>
<td>Webkit</td>
<td>Safari 3.0</td>
<td>OSX.4+</td>
<td>522.1</td>
<td>A</td>
</tr>
<tr>
<td>Webkit</td>
<td>OmniWeb 5.5</td>
<td>OSX.4+</td>
<td>420</td>
<td>A</td>
</tr>
<tr>
<td>Webkit</td>
<td>iPod Touch / iPhone</td>
<td>iPod</td>
<td>420.1</td>
<td>A</td>
</tr>
<tr>
<td>Webkit</td>
<td>S60</td>
<td>S60</td>
<td>413</td>
<td>A</td>
</tr>
<tr>
<td>Presto</td>
<td>Opera 7.0</td>
<td>Win 95+ / OSX.1+</td>
<td>-</td>
<td>A</td>
</tr>
<tr>
<td>Presto</td>
<td>Opera 7.5</td>
<td>Win 95+ / OSX.2+</td>
<td>-</td>
<td>A</td>
</tr>
<tr>
<td>Presto</td>
<td>Opera 8.0</td>
<td>Win 95+ / OSX.2+</td>
<td>-</td>
<td>A</td>
</tr>
<tr>
<td>Presto</td>
<td>Opera 8.5</td>
<td>Win 95+ / OSX.2+</td>
<td>-</td>
<td>A</td>
</tr>
<tr>
<td>Presto</td>
<td>Opera 9.0</td>
<td>Win 95+ / OSX.3+</td>
<td>-</td>
<td>A</td>
</tr>
<tr>
<td>Presto</td>
<td>Opera 9.2</td>
<td>Win 88+ / OSX.3+</td>
<td>-</td>
<td>A</td>
</tr>
<tr>
<td>Presto</td>
<td>Opera 9.5</td>
<td>Win 88+ / OSX.3+</td>
<td>-</td>
<td>A</td>
</tr>
<tr>
<td>Presto</td>
<td>Opera for Wii</td>
<td>Wii</td>
<td>-</td>
<td>A</td>
</tr>
<tr>
<td>Presto</td>
<td>Nokia N800</td>
<td>N800</td>
<td>-</td>
<td>A</td>
</tr>
<tr>
<td>Presto</td>
<td>Nintendo DS browser</td>
<td>Nintendo DS</td>
<td>8.5</td>
<td>C/A<sup>1</sup></td>
</tr>
<tr>
<td>KHTML</td>
<td>Konqureror 3.1</td>
<td>KDE 3.1</td>
<td>3.1</td>
<td>C</td>
</tr>
<tr>
<td>KHTML</td>
<td>Konqureror 3.3</td>
<td>KDE 3.3</td>
<td>3.3</td>
<td>A</td>
</tr>
<tr>
<td>KHTML</td>
<td>Konqureror 3.5</td>
<td>KDE 3.5</td>
<td>3.5</td>
<td>A</td>
</tr>
<tr>
<td>Tasman</td>
<td>Internet Explorer 4.5</td>
<td>Mac OS 8-9</td>
<td>-</td>
<td>X</td>
</tr>
<tr>
<td>Tasman</td>
<td>Internet Explorer 5.1</td>
<td>Mac OS 7.6-9</td>
<td>1</td>
<td>C</td>
</tr>
<tr>
<td>Tasman</td>
<td>Internet Explorer 5.2</td>
<td>Mac OS 8-X</td>
<td>1</td>
<td>C</td>
</tr>
<tr>
<td>Misc</td>
<td>NetFront 3.1</td>
<td>Embedded devices</td>
<td>-</td>
<td>C</td>
</tr>
<tr>
<td>Misc</td>
<td>NetFront 3.4</td>
<td>Embedded devices</td>
<td>-</td>
<td>A</td>
</tr>
<tr>
<td>Misc</td>
<td>Dillo 0.8</td>
<td>Embedded devices</td>
<td>-</td>
<td>X</td>
</tr>
<tr>
<td>Misc</td>
<td>Links</td>
<td>Text only</td>
<td>-</td>
<td>X</td>
</tr>
<tr>
<td>Misc</td>
<td>Lynx</td>
<td>Text only</td>
<td>-</td>
<td>X</td>
</tr>
<tr>
<td>Misc</td>
<td>IE Mobile</td>
<td>Windows Mobile 6</td>
<td>-</td>
<td>C</td>
</tr>
<tr>
<td>Misc</td>
<td>PSP browser</td>
<td>PSP</td>
<td>-</td>
<td>C</td>
</tr>
<tr>
<td>Other browsers</td>
<td>All others</td>
<td>-</td>
<td>-</td>
<td>U</td>
</tr>
</tbody>
</table>
</div>
table.row.add( ... ).draw();
table.searchPanes.rebuild();
remove above lines.
if u wanna use this with server side edit the "dataTables.searchPane.min.js" file as below.
var $jscomp = $jscomp || {}; $jscomp.scope = {}; $jscomp.findInternal = function (a, e, c) { a instanceof String && (a = String(a)); for (var g = a.length, d = 0; d < g; d++) { var l = a[d]; if (e.call(c, l, d, a)) return { i: d, v: l } } return { i: -1, v: void 0 } }; $jscomp.ASSUME_ES5 = !1; $jscomp.ASSUME_NO_NATIVE_MAP = !1; $jscomp.ASSUME_NO_NATIVE_SET = !1; $jscomp.defineProperty = $jscomp.ASSUME_ES5 || "function" == typeof Object.defineProperties ? Object.defineProperty : function (a, e, c) { a != Array.prototype && a != Object.prototype && (a[e] = c.value) };
$jscomp.getGlobal = function (a) { return "undefined" != typeof window && window === a ? a : "undefined" != typeof global && null != global ? global : a }; $jscomp.global = $jscomp.getGlobal(this); $jscomp.polyfill = function (a, e, c, g) { if (e) { c = $jscomp.global; a = a.split("."); for (g = 0; g < a.length - 1; g++) { var d = a[g]; d in c || (c[d] = {}); c = c[d] } a = a[a.length - 1]; g = c[a]; e = e(g); e != g && null != e && $jscomp.defineProperty(c, a, { configurable: !0, writable: !0, value: e }) } };
$jscomp.polyfill("Array.prototype.find", function (a) { return a ? a : function (a, c) { return $jscomp.findInternal(this, a, c).v } }, "es6-impl", "es3");
(function (a) { "function" === typeof define && define.amd ? define(["jquery", "datatables.net"], function (e) { return a(e, window, document) }) : "object" === typeof exports ? module.exports = function (e, c) { e || (e = window); c && c.fn.dataTable || (c = require("datatables.net")(e, c).$); return a(c, e, e.document) } : a(jQuery, window, document) })(function (a, e, c, g) {
function d(b, h) {
var f = this; b = new l.Api(b); this.classes = a.extend(!0, {}, d.classes); this.dom = { container: a("<div/>").addClass(this.classes.container) }; this.c = a.extend(!0, {}, d.defaults,
h); this.s = { dt: b }; b.settings()[0].searchPane = this; b.columns(this.c.columns).eq(0).each(function (a) { f._pane(a) }); a(this.dom.container).on("click", "li", function () { f._toggle(this) }).on("click", "button." + this.classes.clear, function () { f._clear(a(this).closest("div." + f.classes.pane.container)) }); this._attach()
} var l = a.fn.dataTable; a.extend(d.prototype, {
rebuild: function () { var a = this; this.s.dt.columns(this.c.columns).eq(0).each(function (b) { a._pane(b) }) }, _attach: function () {
var b = this.c.container, b = "function" ===
typeof b ? b(this.s.dt) : b; "prepend" === this.c.insert ? a(this.dom.container).prependTo(b) : a(this.dom.container).appendTo(b)
}, _binData: function (a) { var b = {}; a.each(function (a) { a && (b[a] ? b[a]++ : b[a] = 1) }); return b }, _clear: function (a) { var b = this.classes, f = b.item.selected; a.find("li." + f).removeClass(f); a.removeClass(b.pane.active); this.s.dt.column(a.data("column")).search("").draw() }, _pane: function (b) {
var h = this.classes, f = h.item, h = h.pane, c = this.s.dt.column(b), e = a("<ul/>"), d = this._binData(c.data().flatten());
if (!(this._variance(d) < this.c.threshold)) {
for (var g = c.search(), g = g ? g.substr(1, g.length - 2).split("|") : [], m = c.data().unique().sort().toArray(), k = 0, l = m.length; k < l; k++)if (m[k]) { var n = a("<li/>").html('<span class="' + f.label + '">' + m[k] + "</span>").data("filter", m[k]).append(a("<span/>").addClass(f.count).html(d[m[k]])); if (g.length) { var p = m[k].replace ? a.fn.dataTable.util.escapeRegex(m[k]) : m[k]; -1 !== a.inArray(p, g) && n.addClass(f.selected) } e.append(n) } f = a("<div/>").data("column", b).addClass(h.container).addClass(g.length ?
h.active : "").append(a('<button type="button">×</button>').addClass(this.classes.clear)).append(a("<div/>").addClass(h.title).html(a(c.header()).text())).append(a("<div/>").addClass(h.scroller).append(e)); h = this.dom.container; c = h.children().map(function () { if (a(this).data("column") == b) return this }); c.length ? c.replaceWith(f) : a(h).append(f)
}
}, _toggle: function (b) {
var c = this.classes, f = c.item.selected, e = this.s.dt; b = a(b); var d = b.closest("div." + c.pane.container); b.toggleClass(f, !b.hasClass(f)); b = d.find("li." +
f); 0 === b.length ? (d.removeClass(c.pane.active), e.column(d.data("column")).search("").draw()) : (d.addClass(c.pane.active), e.column(d.data("column")).search(a.map(b, function (b) { b = a(b).data("filter").toString(); return a.fn.dataTable.util.escapeRegex(b) }).join("|"), !0, !1).draw())
}, _variance: function (b) { b = a.map(b, function (a, b) { return a }); for (var c = b.length, f = 0, d = 0, e = c; d < e; d++)f += b[d]; for (var f = f / c, g = 0, d = 0, e = c; d < e; d++)g += Math.pow(f - b[d], 2); return g / (c - 1) }
}); d.classes = {
container: "dt-searchPanes", clear: "clear",
pane: { active: "filtering", container: "pane", title: "title", scroller: "scroller" }, item: { selected: "selected", label: "label", count: "count" }
}; d.defaults = { container: function (a) { return a.table().container() }, columns: g, insert: "prepend", threshold: .5 }; d.version = "0.0.1"; a.fn.dataTable.SearchPanes = d; a.fn.DataTable.SearchPanes = d; l.Api.register("searchPanes.rebuild()", function () { return this.iterator("table", function (a) { a.searchPane && a.searchPane.rebuild() }) }); a(c).on("init.dt", function (b, c, e) {
"dt" === b.namespace && (b =
c.oInit.searchPane, e = l.defaults.searchPane, b || e) && (e = a.extend({}, b, e), !1 !== b && new d(c, e))
})
});

Parse html table using HtmlAgilityPack (Linq)

Here's the table structure:
<table class="tb-stock tb-option">
<tr>
<th class="bgc2">col1</th>
<th class="bgc2">col2</th>
<th class="bgc2">col3</th>
</tr>
<tr class="alt-row">
<th class="">2018/1/29</th>
<td class="">0.11</td>
<td class=" b-b">0.50</td>
</tr>
<tr class="alt-row">
<th class="">2018/1/30</th>
<td class="">0.22</td>
<td class=" b-b">0.55</td>
</tr>
</table>
I want to get all the elements below "tr" (including "th" and "td")
How can I use linq to achieve this ?
Problems locate at "..tr.Elements("td|th").."
code:
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.Load(ms, Encoding.UTF8);
List<List<string>> table =
doc.DocumentNode.SelectSingleNode("//table[#class='tb-stock tb-option']")
.Descendants("tr")
.Skip(1)
.Where(tr => tr.Elements("th").Count() >= 1)
.Select(tr => tr.Elements("td|th").Select(td => td.InnerText).ToList())
.ToList();
You can use the following code for extracting inner texts of td or th elements I test it in my local the output is :
2018/1/29
0.11
0.50
2018/1/30
0.22
0.55
You can filter the elements in line :
// both td and th
.Where(node => "td|th".Contains(node.Name))
// only td
.Where(node => "td".Contains(node.Name))
The working code is :
HtmlDocument doc = new HtmlDocument();
doc.Load("test.html", Encoding.UTF8);
List<string> table =
doc.DocumentNode.SelectSingleNode("//table[#class='tb-stock tb-option']")
.Descendants("tr")
.Skip(1)
.Where(tr => tr.Elements("th").Count() >= 1)
.SelectMany(tr => tr.ChildNodes)
.Where(node => "td|th".Contains(node.Name))
.Select(node => node.InnerText)
.ToList();
foreach (var str in table)
{
Console.WriteLine(str);
}

Dynamic javascript form with thymeleaf and Spring-boot

I have a thymeleaf page which successfully uses javascript to generate a form. However I do not know how to make this dynamic form work with spring. Below is my HTML, the form part is down the bottom
HTML
var h1 = document.getElementsByTagName('h1')[0],
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear'),
seconds = 0, minutes = 0, hours = 0,
t;
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
}
function timer() {
clearTimeout(t);
t = setTimeout(add, 1000);
}
/* Start button */
start.onclick = timer;
/* Stop button */
stop.onclick = function() {
clearTimeout(t);
}
/* Clear button */
clear.onclick = function() {
h1.textContent = "00:00:00";
seconds = 0; minutes = 0; hours = 0;
}
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
var count =0;
function addFields(type){
count = count + 1;
var container = document.getElementById("container");
container.appendChild(document.createTextNode("Type"));
var input = document.createElement("input");
input.type = "text";
input.value = type;
container.appendChild(input);
container.appendChild(document.createTextNode(" Timestamp "));
var input = document.createElement("input");
input.type = "text";
input.value = document.getElementById("time").textContent;
container.appendChild(input);
container.appendChild(document.createTextNode(" Details(optional)"));
var input = document.createElement("input");
input.type = "text";
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Match</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" th:href="#{/webjars/bootstrap/3.3.7/css/bootstrap.min.css}"/>
<link rel="stylesheet" type="text/css" th:href="#{/css/main.css}"/>
</head>
<body>
<p th:text="'Match of ' + ${part1} + ' and ' + ${part2}"/>
<p id="demo"></p>
<table>
<tr>
<th>
<p th:text="${part1}"/>
</th>
<th>
<h1 id="time"><time >00:00:00</time></h1>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="clear">clear</button>
</th>
<th>
<p th:text="${part2}"/>
</th>
</tr>
<tr>
<td>
<button onclick="addFields('Ippon')" >Ippon!</button>
</td>
<td>
</td>
<td>
<button onclick="addFields('Ippon')">Ippon!</button>
</td>
</tr>
<tr>
<td>
<button onclick="addFields('Wazari')" >Wazari</button>
</td>
<td>
</td>
<td>
<button onclick="addFields('Wazari')">Wazari</button>
</td>
</tr>
<tr>
<td>
<button onclick="addFields('Shido')" >Shido</button>
</td>
<td>
</td>
<td>
<button onclick="addFields('Shido')">Shido</button>
</td>
</tr>
<tr>
<td>
<button onclick="addFields(' ')" >Event</button>
</td>
<td>
</td>
<td>
<button onclick="addFields(' ')" >Event</button>
</td>
</tr>
</table>
<br/>
Add event
<form action="#" th:action="#{/competition/save}" th:object="${match}" method="post">
<div id="container"></div>
<input type="submit" value="Submit">
</form>
</body>
</html>
Controller
#PostMapping("/competition/save")
public String matchPost(#Valid #RequestBody Match match) {
return "match2";
}
When I hit submit I get "There was an unexpected error (type=Unsupported Media Type, status=415). Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported"

JavaScript to get user input from editable table cell and send to server via json

I created a table with five columns dynamically. Two (the second and third column) of the five columns should be editable on the fly. Each time when user click on one the editable table cell, JavaScript should catch the user input and send the data to the server in json format. I have problem catch the user input and send to the server. Please help. This is my sample code -
<!DOCTYPE html>
<html>
<head>
<title>Editable table</title>
<style type="text/css" title="currentStyle">
#import "css/table.css";
</style>
<script type="text/javascript" language="javascript" src="js/jquery.js"></script>
</head>
<body id="dt_example">
<div id="container">
<div class="full_width big">
Data table<br />
</div>
<div class="editab">
<table border="1">
<thead>
<tr>
<th>Contract Number</th>
<th>Current Status</th>
<th>Sale Balance Amount</th>
<th>Interest Rate</th>
<th>Discount</th>
</tr>
</thead>
<tbody>
<tr>
<td>00123</td>
<td onClick="editTableCell(this)">A30</td>
<td onClick="editTableCell(this)">$1,500.00</td>
<td>3.99 %</td>
<td>140</td>
</tr>
<tr>
<td>00234</td>
<td onClick="editTableCell(this)">B20</td>
<td onClick="editTableCell(this)">$2,500.00</td>
<td>3.99 %</td>
<td>160</td>
</tr>
<tr>
<td>00345</td>
<td onClick="editTableCell(this)">C40</td>
<td onClick="editTableCell(this)">$3,500.00</td>
<td>3.99 %</td>
<td>180</td>
</tr>
<tr>
<td>00456</td>
<td onClick="editTableCell(this)">A20</td>
<td onClick="editTableCell(this)">$4,500.00</td>
<td>3.99 %</td>
<td>200</td>
</tr>
<tr>
<td>00567</td>
<td onClick="editTableCell(this)">B30</td>
<td onClick="editTableCell(this)">$5,500.00</td>
<td>3.99 %</td>
<td>225</td>
</tr>
<tr>
<td>00678</td>
<td onClick="editTableCell(this)">C10</td>
<td onClick="editTableCell(this)">$6,500.00</td>
<td>3.99 %</td>
<td>250</td>
</tr>
<tr>
<td>00789</td>
<td onClick="editTableCell(this)">A30</td>
<td onClick="editTableCell(this)">$7,500.00</td>
<td>3.99 %</td>
<td>300</td>
</tr>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
var SelectState = false;
var SelectedElement = null;
var TextInput = null;
var CellText = null;
var txt = "test";
var idcount = 0;
function editTableCell( e ){
if ( SelectState == false ){
SelectedElement = e;
CellText = e.innerHTML;
e.innerHTML = "";
var objInput = document.createElement("input");
objInput.type = 'text';
objInput.value = CellText;
objInput.id = "txt" + idcount++;
objInput.onkeypress = editTextBox;
objInput.size = 15;
TextInput = objInput;
e.appendChild(objInput);
SelectState = true;
} else if (e != SelectedElement) {
SelectedElement.innerHTML = CellText;
SelectState = false;
}
}
function editTextBox( e ){
if (navigator.appName == "Microsoft Internet Explorer"){
e = window.event;
key = e.keyCode;
}
else if (navigator.appName == "Netscape"){
key = e.which;
}
if ( key == 13 ){
SelectedElement.innerHTML = TextInput.value;
SelectState = false;
}
else if ( key == 27 ){
SelectedElement.innerHTML = CellText;
SelectState = false;
}
}
/* var attrName = "":
var attrValue = "";
if ($('#test1')
{
attrName= "editField01";
attrValue = $(#test1).val();
}
if ($('#test2')
{
attrName= "editField02";
attrValue = $(#test2).val();
}
if ($('#test3')
{
attrName= "editField03";
attrValue = $(#test3).val();
}
var values = '{"' + attrName + '":' + attrValue + '}';
$.ajax({
url: serverUrl + "/abc/contract/" + poolId,
async: false,
type: "PUT",
data: JSON.stringify(values),
dataType: 'json',
processData: false,
contentType: 'application/json',
success: showResponse(json) {
// TODO: What info is returned in the data structure?
showResponse;
},
error: function(err) {
alert("Failed to update the attribute");
htmlErrorDialog(err.responseText);
}
});*/
function showResponse(json) {
if(json.success){
// handle successful response here
alert("user input from column sent successfully!");
} else {
// handle unsuccessful response here
alert("user input fail to send. Please try again");
}
}
</script>
</body>
</html>
You're not actually passing the json data to showResponse:
success: showResponse(json) {
// TODO: What info is returned in the data structure?
showResponse;
},
Pass it along as so, and make sure that json is an actual object and that you don't need to parse it first:
success: function(json) {
// check that json is an actual object via an alert
// alert(json);
showResponse(json);
},
EDIT: Okay after a lot of working around, I have a simple test case for making the fields editable. Please note it uses jquery, and comments are inline:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<!-- Date: 2011-05-10 -->
</head>
<body>
<form>
<table border="1">
<thead>
<tr>
<th>Contract Number</th>
<th>Current Status</th>
<th>Sale Balance Amount</th>
<th>Interest Rate</th>
<th>Discount</th>
</tr>
</thead>
<tbody>
<tr>
<!-- The "identifier" class makes it so we have an id
to pass to our ajax script so we know what to change -->
<td class="identifier">00123</td>
<td class="editable">A30</td>
<td class="editable">$1,500.00</td>
<td>3.99 %</td>
<td>140</td>
</tr>
</tbody>
</table>
</form>
<script type="text/javascript">
// bind our event handler to all td elements with class editable
$('td.editable').bind('click', function() {
// Only create an editable input if one doesn't exist
if(!$(this).has('input').length) {
// Get the text from the cell containing the value
var value = $(this).html();
// Create a new input element with the value of the cell text
var input = $('<input/>', {
'type':'text',
'value':value,
// Give it an onchange handler so when the data is changed
// It will do the ajax call
change: function() {
var new_value = $(this).val();
// This finds the sibling td element with class identifier so we have
// an id to pass to the ajax call
var cell = $(this).parent();
// Get the position of the td cell...
var cell_index = $(this).parent().parent().children().index(cell);
// .. to find its corresponding header
var identifier = $('thead th:eq('+cell_index+')').html();
//ajax post with id and new value
$(this).replaceWith(new_value);
}
});
// Empty out the cell contents...
$(this).empty();
// ... and replace it with the input field that has the value populated
$(this).append(input);
}
});
</script>
</body>

MVC view freeze

I have a strange issue. I've got create and edit view with it controller. Everything works fine, but (for example) if I don't enter a value, the validation #Html.ValidationSummary(False) returns the message error. The problem is when there is an error because the browser freeze and consume a lot of resources (memory) but after 4 or 5 minutes waiting, the view is rendered with the data and validation messages.
The server is: Windows 2003 Standard Edition, SQLServer 2008 Standard Edition, IIS6.0.
In development enviroment it's the same problem.
I'm using VS2010 SP1 with razor and MVC3. This issue happended in VS2008 SP1 with aspx and MVC2 too.
Someone knows what it's going on?
Regards.
Because it's reduce code maybe there is an error but the original it's fine. Of course all javascript and jquery calls exits
Edit view
#ModelType iSAM.Certificados
#Code
ViewData("Title") = "Edit"
Layout = "~/Views/Shared/CertificadosLayout.vbhtml"
End Code
#section Contenido
#Using Html.BeginForm()
#<fieldset>
<legend></legend>
<br />
<fieldset>
<legend>Datos Generales</legend>
<table>
<tr>
<td style="border-width:0px; border-style:solid">
#Html.LabelFor(Function(Model) Model.IDCertificado)
#Html.TextBoxFor(Function(Model) Model.IDCertificado, New With {.readonly = "readonly", .style = "width:90px; text-align:center", .class = "letraingreso"})
</td>
<td style="width:20px"></td>
<td style="border-width:0px; border-style:solid">
#Html.LabelFor(Function(Model) Model.IDPoliza)
#Html.DropDownListFor(Function(Model) Model.IDPoliza, Nothing, New With {.style = "width:200px; visibility:visible", .class = "letraingreso"})
</td>
</tr>
<tr>
<td style="border-width:0px; border-style:solid">
#Html.LabelFor(Function(Model) Model.IDCampaña)
#Html.DropDownListFor(Function(Model) Model.IDCampaña, Nothing, New With {.style = "width:250px; visibility:visible", .class = "letraingreso"})
</td>
<td style="width:20px"></td>
<td style="border-width:0px; border-style:solid">
#Html.LabelFor(Function(Model) Model.IDVigencia)
#Html.DropDownListFor(Function(Model) Model.IDVigencia, Nothing, New With {.style = "width:183px; visibility:visible", .class = "letraingreso", .disabled = "disabled"})
</td>
</tr>
</table>
</fieldset>
<br />
<div id="tabs">
#*Establece los tabs a ser creados*#
<ul>
<li><span>Asegurado</span></li>
</ul>
#*Asegurados*#
<div id="fragment-1">
<table>
<tr>
<td style="border-width:0px; border-style:solid">
#Html.LabelFor(Function(Model) Model.IDAsegurado)
#Html.TextBoxFor(Function(Model) Model.IDAsegurado, New With {.readonly = "readonly", .style = "width:80px; text-align:center", .class = "letraingreso"})
</td>
<td style="width:20px"></td>
<td style="border-width:0px; border-style:solid">
#Html.LabelFor(Function(Model) Model.IDTipoDocumentoAsegurado)
#Html.DropDownListFor(Function(Model) Model.IDTipoDocumentoAsegurado, Nothing, New With {.style = "width:200px; visibility:visible", .class = "letraingreso"})
</td>
<td style="width:20px"></td>
<td style="border-width:0px; border-style:solid">
#Html.LabelFor(Function(Model) Model.NumeroDocumentoAsegurado)
#Html.TextBoxFor(Function(Model) Model.NumeroDocumentoAsegurado, New With {.onkeyup = "if(this.value.match(/\D/))this.value=this.value.replace(/\D/g,'')", .class = "letraingreso", .style = "width:100px"})
</td>
<td style="width:20px"></td>
<td style="border-width:0px; border-style:solid">
#Html.LabelFor(Function(Model) Model.FechaNacimientoAsegurado)
#Html.TextBox("FechaNacimientoAsegurado", Format(Model.FechaNacimientoAsegurado, "dd/MM/yyyy"), New With {.maxLength = "10", .onkeyup = "DateFormat(this, this.value, event, false, '3')", .onblur = "DateFormat(this, this.value, event, true, '3')", .style = "width:80px", .class = "letraingreso"})
<img src="#Url.Content("~/Images/spacer.gif")" class="imagenfecha" style="border:0" height="16px" width="20px" id="imgFechaNacimientoAsegurado" alt="" />
<script type="text/javascript">
Calendar.setup(
{
inputField: "FechaNacimientoAsegurado",
ifFormat: "%d/%m/%Y",
button: "imgFechaNacimientoAsegurado",
align: "Tl",
singleClick: true
});
</script>
</td>
</tr>
</table>
<table>
<tr>
<td style="border-width:0px; border-style:solid">
#Html.LabelFor(Function(Model) Model.NombresAsegurado)
#Html.TextBoxFor(Function(Model) Model.NombresAsegurado, New With {.style = "text-transform:uppercase; width:270px", .class = "letraingreso"})
</td>
<td style="width:20px"></td>
<td style="border-width:0px; border-style:solid">
#Html.LabelFor(Function(Model) Model.PrimerApellidoAsegurado)
#Html.TextBoxFor(Function(Model) Model.PrimerApellidoAsegurado, New With {.style = "text-transform:uppercase; width:182px", .class = "letraingreso"})
</td>
<td style="width:20px"></td>
<td style="border-width:0px; border-style:solid">
#Html.LabelFor(Function(Model) Model.SegundoApellidoAsegurado)
#Html.TextBoxFor(Function(Model) Model.SegundoApellidoAsegurado, New With {.style = "text-transform:uppercase; width:182px", .class = "letraingreso"})
</td>
</tr>
</table>
<table>
<tr>
<td style="border-width:0px; border-style:solid">
#Html.LabelFor(Function(Model) Model.IDCiudadAsegurado)
#Html.DropDownListFor(Function(Model) Model.IDCiudadAsegurado, Nothing, New With {.style = "width:180px; visibility:visible", .class = "letraingreso"})
</td>
<td style="width:15px"></td>
<td style="border-width:0px; border-style:solid">
#Html.LabelFor(Function(Model) Model.DireccionDomicilioAsegurado)
#Html.TextBoxFor(Function(Model) Model.DireccionDomicilioAsegurado, New With {.style = "text-transform:uppercase; width:354px", .class = "letraingreso"})
</td>
<td style="width:20px"></td>
<td style="border-width:0px; border-style:solid">
#Html.LabelFor(Function(Model) Model.CorreoElectronicoAsegurado)
#Html.TextBoxFor(Function(Model) Model.CorreoElectronicoAsegurado, New With {.class = "letraingreso", .style = "width:170px"})
</td>
</tr>
</table>
<table>
<tr>
<td style="border-width:0px; border-style:solid">
#Html.LabelFor(Function(Model) Model.IDGeneroAsegurado)
#Html.DropDownListFor(Function(Model) Model.IDGeneroAsegurado, Nothing, New With {.style = "width:98px; visibility:visible", .class = "letraingreso"})
</td>
<td style="width:15px"></td>
<td style="border-width:0px; border-style:solid">
#Html.LabelFor(Function(Model) Model.IDEstadoCivilAsegurado)
#Html.DropDownListFor(Function(Model) Model.IDEstadoCivilAsegurado, Nothing, New With {.style = "width:120px; visibility:visible", .class = "letraingreso"})
</td>
<td style="width:15px"></td>
<td style="border-width:0px; border-style:solid">
#Html.LabelFor(Function(Model) Model.TelefonoFijoAsegurado)
#Html.TextBoxFor(Function(Model) Model.TelefonoFijoAsegurado, New With {.class = "letraingreso", .style = "width:80px", .onkeydown = "javascript:return dFilter (event.keyCode, this, '###-##-####');"})
</td>
<td style="width:15px"></td>
<td style="border-width:0px; border-style:solid">
#Html.LabelFor(Function(Model) Model.TelefonoCelularAsegurado)
#Html.TextBoxFor(Function(Model) Model.TelefonoCelularAsegurado, New With {.class = "letraingreso", .style = "width:80px", .onkeydown = "javascript:return dFilter (event.keyCode, this, '###-##-####');"})
</td>
</tr>
</table>
<br />
</div>
</div>
<br />
<fieldset>
<legend>Observaciones</legend>
#Html.LabelFor(Function(Model) Model.Observaciones)
#Html.TextBoxFor(Function(Model) Model.Observaciones, New With {.class = "letraingreso", .style = "width:90%; text-transform:uppercase"})
</fieldset>
</fieldset>
#<div style="display:none; position:absolute; margin:auto; left:0; right:0; text-align:center" id="inprogress">
<br /><br /><br /><br /><br /><br />
<img id="inprogress_img" src="#Url.Content("~/Images/loading.gif")" alt="Procesando..." />
<br />
Por favor espere mientras su solicitud es procesada...
</div>
#<p>
<input type="submit" value="Guardar" id="cmdGuardar" onclick="return doSubmit()" />
</p>
#<div>
#Html.ActionLink(" ", "ListarCertificadosVehiculos", "CertificadosLayout", New With {.area = ""}, New With {.class = "imgRegresar", .title = "Regresar"})
</div>
End Using
End Section
Class (remember it's a reduce code)
Imports System.ComponentModel
Imports System.ComponentModel.DataAnnotations
Public Class Certificados
Private varIDCertificado As Long
Private varIDPoliza As Long
Private varNumeroPoliza As Long
Private varIDCampaña As Long
Private varIDVigencia As Long
<DisplayName("Número de Certificado:")> _
Public Property IDCertificado() As Long
Get
Return varIDCertificado
End Get
Set(ByVal value As Long)
varIDCertificado = value
End Set
End Property
<Required(ErrorMessage:="Debe seleccionar la poliza correspondinete")> _
<DisplayName("Número de Poliza:")> _
Public Property IDPoliza() As Long
Get
Return varIDPoliza
End Get
Set(ByVal value As Long)
varIDPoliza = value
End Set
End Property
<DisplayName("Número de Poliza:")> _
Public Property NumeroPoliza() As Long
Get
Return varNumeroPoliza
End Get
Set(ByVal value As Long)
varNumeroPoliza = value
End Set
End Property
End Class
Service (If return False the problem that I said appears)
Public Function EditarCertificadoVehiculo(ByVal parCertificado As CERTIFICADO, ByVal parIDTarjetaCredito As String, ByVal parIDEstado As Long, _
ByVal parLugarTrabajoAsegurado As LUGAR_DE_TRABAJO, ByVal parIDCiudadLugarTrabajo As Long, ByVal parLugarTrabajoPagador As LUGAR_DE_TRABAJO, ByVal parIDCiudadLugarTrabajoPagador As Long, _
ByVal parAsegurado As ASEGURADO, ByVal parIDTipoDocumento As Long, ByVal parIDCiudadNacimiento As Long, ByVal parIDGenero As Long, ByVal parIDEstadoCivil As Long, _
ByVal parPagador As ASEGURADO, ByVal parIDTipoDocumentoPagador As Long, ByVal parIDCiudadNacimientoPagador As Long, ByVal parIDGeneroPagador As Long, ByVal parIDEstadoCivilPagador As Long, _
ByVal parConductor As CONDUCTOR, _
ByVal parConcesionario As CONCESIONARIO, _
ByVal parVehiculo As VEHICULO, ByVal parIDMarca As Long, ByVal parIDModelo As Long, ByVal parIDTipoPlaca As Long, ByVal parIDUsoVehiculo As Long, ByVal parIDColor As Long, _
ByVal parArregloTasas As ArrayList, ByVal parArregloExtras(,) As String) As Boolean Implements IiSAMService.EditarCertificadoVehiculo
If Not ValidarCertificadoVehiculo(parCertificado, parIDTarjetaCredito, parAsegurado, parLugarTrabajoAsegurado, parPagador, parLugarTrabajoPagador, parVehiculo, parIDTipoPlaca, parConcesionario, parArregloTasas, parIDEstado) Then
Return False
End If
Try
varRepositorio.EditarCertificadoVehiculo(parCertificado, parIDTarjetaCredito, parIDEstado, _
parLugarTrabajoAsegurado, parIDCiudadLugarTrabajo, parLugarTrabajoPagador, parIDCiudadLugarTrabajoPagador, _
parAsegurado, parIDTipoDocumento, parIDCiudadNacimiento, parIDGenero, parIDEstadoCivil, _
parPagador, parIDTipoDocumentoPagador, parIDCiudadNacimientoPagador, parIDGeneroPagador, parIDEstadoCivilPagador, _
parConductor, _
parConcesionario, _
parVehiculo, parIDMarca, parIDModelo, parIDTipoPlaca, parIDUsoVehiculo, parIDColor, _
parArregloTasas, parArregloExtras)
Catch ex As Exception
varDiccionarioValidacion.AddError("EditarCertificadoVehiculo", ex)
Return False
End Try
Return True
End Function
Ok. I tried with google chrome browser and the browser freeze for few minutes like IE8, but chrome do not crashed. So I could to see that a dropdownlist load thousands of records (maybe 100000-- my mistake).
This is the corrected line:
If String.IsNullOrEmpty(Request.Form("NombreLugarTrabajoAsegurado")) Then
varListado = New SelectList(varServicio.ListarLugaresTrabajoPorNombre("NO DEFINIDO", True, True), "ID_LUGAR_TRABAJO", "NOMBRE_LUGAR_TRABAJO")
Else
varListado = New SelectList(varServicio.ListarLugaresTrabajoPorNombre(Request.Form("NombreLugarTrabajoAsegurado"), True, True), "ID_LUGAR_TRABAJO", "NOMBRE_LUGAR_TRABAJO", Request.Form("IDLugarTrabajoAsegurado"))
End If
ViewData("IDLugarTrabajoAsegurado") = varListado
Maybe IE team needs to fix this to prevent crashes.
I hope this helps someone else.

Resources