Show data from Model(Dictionary) in html table using jquery - c#

I am using ASP.Net Razor , ASP.NET MVC and jQuery.
I have a dictionary in Model and a drop down list in html table. What I want is , when I select "ALM" option in drop down list , I want to show some data from dictionary in id="leftValues" using jquery .
My code:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
#model Dictionary<string,string>
<style type="text/css">
#myTable {
position:absolute;
top:10%;
left:30%;
}
#heading {
text-align: center
}
#SelectPlatform {
text-align: center;
position: absolute;
top: 10%;
}
</style>
<table id="myTable">
<tr>
<th id="heading"> Select Platform </th>
<th id="heading"> Available Options</th>
<th></th>
<th id="heading"> Selected Options</th>
</tr>
<tr>
<td>
<select id="SelectPlatform">
<option>Select Platform</option>
<option>ALM</option>
<option>Serena</option>
</select>
</td>
<td>
<div>
<select style="text-align: center; text-wrap:normal; width: 110%"; size="20%" id="leftValues" multiple >
// Here I want to show data from dictionary
</select>
</div>
</td>
<td>
<div>
<input style="width: 100%" type="button" id="btnLeft" value="<<" />
<input style="width: 100%" type="button" id="btnRight" value=">>" />
</div>
</td>
<td>
<div>
<select style="text-align: center; text-wrap:normal; width: 110%" id="rightValues" size="20%" multiple >
</select>
</div>
</td>
</tr>
</table>
<script type="text/javascript">
$(document).ready(function () {
$("#SelectPlatform").change(function () {
var textValue = $("#SelectPlatform option:selected").text();
if (textValue == "Select Platform")
{
// some code
}
else if (textValue == "ALM")
{
// this is working
$("#leftValues").append('<option value=' + '"NoItem"' + ' >HI I am added </option>');
// this is not working
$.each(Model, function (key, value) {
alert(key);
alert(value);
$("#leftValues").append('<option value=' + '"NoItem"' + ' >HI I am also added </option>');
});
}
else if (textValue == "Serena")
{
// some code
}
});
}
});
</script>

So you need to move the Model values from the front end to the back end. Javascript cannot read ViewModel values as they are processed on the server. You can write them out into javascript though:
<script>
var dicMap = new Map();
#foreach (var kv in Model)
{
#:dicMap.set(#kv.Key, #kv.Value);
}
</script>
now change:
// this is not working
$.each(dicMap, function (key, value) {

Related

I want to serialize form data using jquery

Hello guys i working on data serialize using jquery
i have pasted my HTML code below.
HTML
<div class="row">
<div class="col-md-12 col-sm-12">
<div class="ibox-content">
<form id="product">
<table class="table">
<thead>
<tr>
<th>Action</th>
<th>Product Name</th>
<th>Price</th>
<th>Qty</th>
<th>Total</th>
</tr>
</thead>
<tbody>
#foreach (var _product in Model.ProductList)
{
<tr>
<td>Details</td>
<td>
<strong>
#_product.name
<input type="hidden" name="productId" value="#_product.productId" />
</strong>
</td>
<td id="price">#_product.wholesalePrice</td>
<td id="quantity"><input style="width:50px;" name="qty" value="0"><input type="hidden" name="total" id="rowTotal" /></td>
<td id="value"></td>
</tr>
}
</tbody>
</table>
</form>
<div class="ibox-content">
<button id="totalCal" class="btn btn-primary pull-right">Calculate</button>
</div>
<table class="table invoice-total">
<tbody>
<tr>
<td><strong>Sub Total :</strong></td>
<td id="result">$1026.00</td>
</tr>
<tr>
<td><strong>Shipping :</strong></td>
<td id="Shipping">$235.98</td>
</tr>
<tr>
<td><strong>TOTAL :</strong></td>
<td id="finalTotal">$1261.98</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
Jquery function
function GetTblRow() {
var data = $("#product").serializeArray();
var from = JSON.stringify(data);
console.log(from);
};
Output
[{"name":"productId","value":"1"},{"name":"qty","value":"0"},{"name":"total","value":"0"},{"name":"productId","value":"2"},{"name":"qty","value":"0"},{"name":"total","value":"0"},{"name":"productId","value":"3"},{"name":"qty","value":"0"},{"name":"total","value":"0"},{"name":"productId","value":"4"},{"name":"qty","value":"0"},{"name":"total","value":"0"},{"name":"productId","value":"5"},{"name":"qty","value":"0"},{"name":"total","value":"0"},{"name":"productId","value":"6"},{"name":"qty","value":"0"},{"name":"total","value":"0"},{"name":"productId","value":"7"},{"name":"qty","value":"0"},{"name":"total","value":"0"},{"name":"productId","value":"8"},{"name":"qty","value":"0"},{"name":"total","value":"0"},{"name":"productId","value":"9"},{"name":"qty","value":"0"},{"name":"total","value":"0"},{"name":"productId","value":"10"},{"name":"qty","value":"0"},{"name":"total","value":"0"},{"name":"productId","value":"12"},{"name":"qty","value":"0"},{"name":"total","value":"0"},{"name":"productId","value":"13"},{"name":"qty","value":"0"},{"name":"total","value":"0"}]
Expected Output
[{"ProductId":"1","qty":"0","total":"0"},"ProductId":"1","qty":"0","total":"0"},{"ProductId":"2","qty":"0","total":"0"},{"ProductId":"3","qty":"0","total":"0"},{"ProductId":"4","qty":"0","total":"0"}]
i did above code for serialize form data but i can not get above expected output. So can you help me with this?
you cannot directly use serializeArray() to get the expected json you have to separate the expected result from array
<script>
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function() {
$("#totalCal").click(function(){
alert(JSON.stringify($('#product').serializeObject()));
return false;
});
});
</script>
You can use some custom code to format your array. Here is the simplest solution:
function getFormattedArray(array){
var result = [];
for(var currentPosition = 0;currentPosition < array.length; currentPosition += 3) {
result.push({ProductId: array[currentPosition].value,
qty: array[currentPosition+1].value,
total: array[currentPosition+1].value});
}
return result;
}

Need to create textboxes dynamically without loosing the style

In my we form, I have a textbox where an integer can be placed and by clicking the button next to it, It should dynamically create that many textboxes as a table. The jQuery code for which is:
$("#ContentPlaceHolder1_LnkBtnNoofItems").click(function () {
$(".white-table-view-block").removeClass("hide");
$("#Table-id-Name").removeClass("hide");
$("#Table-id-Name").each(function () {
var NumbRow = $("#txtNoofItems").val();
var htmlvar = '';
for (i = 0; i < NumbRow; i++) {
htmlvar += '<tr>';
htmlvar += '<td class="blanck-space"> </td>';
htmlvar += '<td class="item-number"><input type="text" id="item_number_input' + i + '" class="form-control" placeholder="Number" /></td>';
htmlvar += '<td class="item-description"><input type="text" id="item_des_input' + i + '" class="form-control" placeholder="Number" /></td>';
htmlvar += '<td class="item-quantity"><input type="text" id="item_quantity_input' + i + '" class="form-control" placeholder="Pieces" /></td>';
htmlvar += '<td class="item-cost"><input type="text" id="item_cost_input' + i + '" class="form-control" placeholder="$" /></td>';
htmlvar += '<td class="item-value"><input type="text" id="item_total_input' + i + '" class="form-control" placeholder="$" /></td>';
htmlvar += '<td class="item-action"><img src="images/icon-delete.png" alt="" /></td>';
htmlvar += '</tr>';
}
$('.tbody-content').append(htmlvar);
$(".delet-icon").click(function () {
$(this).parents("tr").remove();
});
});
});
The textbox and link button code is:
<div class="col-md-4 col-lg-2">
<div class="number-of-item-block">
<div class="row">
<div class="col-md-12"><asp:label runat="server" ID="lblNoofItems" Text="No. of Item Rows"></asp:label></div>
<div class="col-md-12">
<asp:TextBox runat="server" class="form-control" id="txtNoofItems" placeholder="#" ></asp:TextBox> <asp:Linkbutton runat="server" ID="LnkBtnNoofItems" class="btn btn-dark-blue"><i class="glyphicon glyphicon-plus"></i></asp:Linkbutton>
<div class="row">
<div class="col-md-6"></div>
<div class="col-md-6"></div>
</div>
</div>
</div>
</div>
</div>
But the text boxes which should be generated are controls which need to be working on server side. Please tell me how can I do this. I did not do this before and I have no idea how to do them now.
Thanks,
Deepak
I think this may help you out..
$("#aAddMoreLicense").click(function () {
AddMoreKeyword();
return false;
});
//delete added Row or unwanted row
function DeleteLicense($aDelete) {
if ($(".tbl-Keyword tbody tr").length > 1) {
$($aDelete.closest("tr")).remove();
}
AllowDeleteFunctionality();
}
function AllowDeleteFunctionality() {
debugger
if ($(".tbl-Keyword tbody tr").length === 2) {
$(".tbl-Keyword tbody tr").each(function () {
if ($(this).attr("class") !== "hidden for-clone") {
$(this).find(".aDelete-Keyword").addClass("hidden");
}
});
}
else {
$(".tbl-Keyword tbody tr").each(function () {
if ($(this).attr("class") !== "hidden for-clone") {
$(this).find(".aDelete-Keyword").removeClass("hidden");
}
});
}
}
AddMoreKeyword();
function AddMoreKeyword() {
var rowIndex = $(".tbl-Keyword tbody tr").length;
var trItems = $(".tbl-Keyword tbody tr").eq(0).clone(true);
trItems.removeClass("hidden for-clone");
trItems.addClass("Keyword-row-" + rowIndex);
$("#txtSearchKeyword", trItems).val("");
$("#lblSrNo", trItems).addClass("Keyword-lbl-" + rowIndex);
$("#lblSrNo", trItems).text(rowIndex);
$("#txtSearchKeyword", trItems).addClass("Keyword-type-" + rowIndex);
$("#ddlDomainRank1", trItems).addClass("Keyword-no-" + rowIndex);
$(".tbl-Keyword tbody").append(trItems);
AllowDeleteFunctionality();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" />
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" /></script>
<div class="main-box" style="border: none; box-shadow: none">
<div class="main-box-body clearfix Scroll">
<div class="col-lg-12" style="margin: 10px 0px;">
<span class="mandatory" id="spnlbl" style="font-weight: bold; font-size: 12pt">*</span>
</div>
<table class="table tbl-Keyword" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th style="width: 3% !important;">
Keyword Sr#
</th>
<th style="width: 80% !important;">
<span>Keyword</span>
<span style="color: red">*</span>
</th>
<th style="width: 15% !important;">
<span >Rank</span>
<span style="color: red">*</span>
</th>
<th style="width: 3% !important;">
<span> Linked HRA</span>
</th>
<th style="width: 3% !important;">
Delete
</th>
</tr>
</thead>
<tbody>
<tr class="hidden for-clone">
<td style="width: 3%">
<span ID="lblSrNo" ></span>
</td>
<td style="width: 80% !important; padding: 5px 8px;" class="td">
<input type="hidden" id="hdfArtVideoId" />
<input type="hidden" id="hdfType" />
<input type="text" ID="txtSearchKeyword" CssClass="form-control" AutoCompleteType="Disabled" />
<div class="ac_keywordresults hidden" style="position: absolute; width: 300px; max-height: 184px; overflow: auto;">
</div>
</td>
<td style="width: 15% !important; padding: 5px 8px;">
<select ID="ddlDomainRank1" CssClass="form-control ddlRank" Style="padding: 6px 8px; float: left">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</td>
<td style="width: 3% !important; text-align: center">
<a onclick="LinkedHra(this);" class="aLContent-Keyword" style="color: #8bc34a !important; font-size: 25px" href="javascript:void(0);" title="Linked Content" target="_blank"><i class="glyphicon glyphicon-list-alt"></i></a>
</td>
<td style="width: 3% !important; text-align: center;">
<a onclick="DeleteLicense(this);" class="aDelete-Keyword" style="color: #8bc34a !important;" href="javascript:void(0);" title="Delete"><i class="glyphicon glyphicon-trash"></i></a>
</td>
</tr>
</tbody>
</table>
<div class="col-md-12 form-group">
<i class="glyphicon glyphicon-plus"></i> Add Keywords
</div>
</div>
</div>

HTML view page save as PDF using roatativa

I have following image for the Create_Brochure ActionResult in Brochure Contrller Class
Here the whole URL of that Action
http://localhost:49669/Brochure/Create_Brochure?%5B0%5D.Property_ID=1&%5B0%5D.IsChecked=true&%5B0%5D.IsChecked=false&%5B1%5D.Property_ID=2&%5B1%5D.IsChecked=true&%5B1%5D.IsChecked=false&%5B2%5D.Property_ID=3&%5B2%5D.IsChecked=true&%5B2%5D.IsChecked=false&%5B3%5D.Property_ID=4&%5B3%5D.IsChecked=false&%5B4%5D.Property_ID=5&%5B4%5D.IsChecked=false&%5B5%5D.Property_ID=6&%5B5%5D.IsChecked=false&%5B6%5D.Property_ID=7&%5B6%5D.IsChecked=false&%5B7%5D.Property_ID=8&%5B7%5D.IsChecked=false&%5B8%5D.Property_ID=9&%5B8%5D.IsChecked=false&%5B9%5D.Property_ID=10&%5B9%5D.IsChecked=false
Once I click I want to save this view page as PDF , to do that I followed this tutorial
So this is the cshtml view page , so it doesn't have a model class
#model IEnumerable<int>
#{
ViewBag.Title = "Create Template";
}
<!DOCTYPE html>
<html>
<head>
<title>Create a Template</title>
</head>
<body>
<div style="width:100%; padding:10px; float:left;">
<table width=1100 cellpadding=10>
<tr>
<td colspan="2">
<div id="topper" style="font-family:'Segoe UI';background-color: black;color: white;clear: both;text-align: center;padding: 5px;border-radius:15px 15px 0px 0px;">
Bank Brochure
</div>
</td>
</tr>
#if (Model.Contains(1))
{
<tr>
<td colspan="2">
<div id="header" style="font-family: 'Segoe UI';background-color: slategray; color: white; text-align: center; padding: 5px;">
<h1 style="font-family: 'Segoe UI'; color: black; text-align: center;" contentEditable='True'>Product Name</h1>
</div>
</td>
</tr>
}
#if (Model.Contains(2))
{
<tr>
<td colspan="2" style="background-color:lightgrey">
<div id="header" style="font-family: 'Segoe UI';color: white; text-align: center; padding: 5px;border-radius">
<h2 style="font-family: 'Segoe UI'; color: black;float:left" contentEditable='True'>Product Description</h2>
<p style="font-family: 'Segoe UI'; color: black;float:left" contentEditable='True'>London is the capital city of England. It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.Standing on the River Thames London has been a major settlement for two millennia, its history going back to its founding by the Romans, who named it Londinium.</p>
</div>
</td>
</tr>
}
#if (Model.Contains(3))
{
<tr>
<td colspan="2">
<div id="header" style="font-family: 'Segoe UI';background-color: steelblue; color: white; text-align: center; padding: 5px;">
<h3 style="font-family: 'Segoe UI'; color: white; text-align: center;font-style:italic" contentEditable='True'>"Unique Selling Propositions It enables ASP.NET Web developers to replace any textbox with an intuitive Word-like WYSIWYG html editor.
"</h3>
</div>
</td>
</tr>
}
#if()....
<tr>
<td colspan="2">
<div id="footer" style="font-family:'Segoe UI';background-color: black;color: white;clear: both;text-align: center;padding: 5px;border-radius:0px 0px 15px 15px;">
Copyright © 2015 Zoo Group , Solution by kelum.
</div>
</td>
</tr>
</table>
</div>
<br />
<button id="btn_sumbit" type="button" class="btn btn-danger submit">Save as PDF</button>
</body>
</html>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jqueryui")
<script type="text/javascript">
$('#btn_sumbit').on('click', function () {
$.ajax({
type: "POST",
url: '#Url.Action("DownloadActionAsPDF", "Brochure")',
dataType: "text",
data: null,
success: function (data) {
},
error: console.log("it did not work"),
});
});
</script>
}
this is controller class method to save to PDF
[HttpPost]
public ActionResult DownloadActionAsPDF()
{
string path = Request.Url.ToString();
//Request.Url.ToString() using to get current page URL
return new Rotativa.UrlAsPdf(path) { FileName = "UrlTest.pdf" };
}
but once I click this button it doesn't save to PDF file,
As i already commented that your code is calling the same Method again and again..
You can do the same thing by using ActionAsPdf and point it to the Create_Brochure Action method of yours
Ex:-
public ActionResult DownloadActionAsPDF()
{
return new Rotativa.ActionAsPdf("Create_Brochure") { FileName = "TestPdf.pdf"};
}
public ActionResult Create_Brochure()
{
//Your logic....
return View()
}
and in your view page no need of a button or a Ajax call can be done by a anchor tag
View:-
<a href="#Url.Action("DownloadActionAsPDF", "MyDiary")" class="btn btn-danger submit" download>SaveAsPdf</a>

Asp.net jQuery works outside, but not inside foreach loop

This is the script I am working with.
$(document).ready(function () {
$('#selectall').click(function () {
$('.selectedId').prop('checked', isChecked('selectall'));
});
});
function isChecked(checkboxId) {
var id = '#' + checkboxId;
return $(id).is(":checked");
}
function resetSelectAll() {
// if all checkbox are selected, check the selectall checkbox
// and viceversa
if ($(".selectedId").length === $(".selectedId:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}
if ($(".selectedId:checked").length > 0) {
$('#edit').attr("disabled", false);
} else {
$('#edit').attr("disabled", true);
}
}
And this is the cshtml view.
<table id="notificationsTableId">
<thead>
<tr role="row">
<th rowspan="1" colspan="1">
<input type="checkbox" id="selectall" />
</th>
</tr>
</thead>
<tbody>
<tr class="results-table-row odd">
<td>
<input type="checkbox" class="selectedId" name="selectedId" onclick="resetSelectAll();"/>
</td>
</tr>
<tr class="results-table-row even">
<td>
<input type="checkbox" class="selectedId" name="selectedId" onclick="resetSelectAll();"/>
</td>
</tr>
<tr class="results-table-row even odd">
<td>
<input type="checkbox" class="selectedId" name="selectedId" onclick="resetSelectAll();" />
</td>
</tr>
</tbody>
</table>
Right now the select button will work like it should, if i check it it will check all the dates inside that table.
But what I want to do is I want that button to select all the Check-boxes on the page.
But if I give a checkbox the same ID inside my foreach loop like this:
#foreach (var date in group)
{
var isoDate = date.ToString("yyMMdd");
var day = date.ToString("ddd", new CultureInfo("sv-SE")).Substring(0, 2);
<label style="padding-left: 10px">
<input type="checkbox" id="selectedId" name="isoDate" value="#isoDate"/>#day-#isoDate
</label>
}
It doesn't work, it will still only select those 3 check-boxes on the top of the page. I would assume it would check all the check-boxes correct?
It ends up like this:
You are using selectedId as id instead of class like other checkboxes. Use it as class attribute as shown below
#foreach (var date in group)
{
var isoDate = date.ToString("yyMMdd");
var day = date.ToString("ddd", new CultureInfo("sv-SE")).Substring(0, 2);
<label style="padding-left: 10px">
<input type="checkbox" class="selectedId" name="isoDate" value="#isoDate"/>#day-#isoDate
</label>
}

`<td>` will be calculated if the display of the `tr` is not none

In my cshtml file, I want the <td> to be calculated if the display of the tr is not none.
<tr id="abc" style="display:none;height: 30px;">
<td class="titleStyle">Page:</td>
<td align="left">#Html.DropDownList(("pages"),
(IEnumerable<SelectListItem>)ViewData["mypages"], new { onchange = "func()",
id = "page2", style = "float:left; width: 276px;height: 20px;" })</td>
so I tried something like:
<script type="text/javascript">
if ($("#abc").css("display") != "none") {
}
</script>
but how can I continue from here?
any help appreciated!
You mean something like this? Using window.getComputedStyle (IE9+)
HTML
<table>
<tbody>
<tr id="abc" style="display:none;height: 30px;">
<td class="titleStyle">Page:</td>
</tr>
<tr id="abcd" style="height: 30px;">
<td class="titleStyle">Page:</td>
</tr>
</tbody>
</table>
Javascript
var trs = document.getElementsByTagName("tr"),
length = trs.length,
i = 0;
while (i < length) {
if (window.getComputedStyle(trs[i]).display !== "none") {
trs[i].children[0].firstChild.nodeValue = "Page: 1";
}
i += 1;
}
On jsfiddle

Categories