jquery loop through li create json process it in c# - c#

I have list of items in database
ITEMS
I_id int,
I_name varchar(50),
I_order int
I displayed it in ul li
<ul id='items'>
<li><span class='txt'>item-1</span> <span class='mOrder'>1</span></li>
<li><span class='txt'>item-2</span> <span class='mOrder'>2</span></li>
<li><span class='txt'>item-3</span> <span class='mOrder'>3</span></li>
<li><span class='txt'>item-4</span> <span class='mOrder'>4</span></li>
<li><span class='txt'>item-5</span> <span class='mOrder'>5</span></li>
<li><span class='txt'>item-6</span> <span class='mOrder'>6</span></li>
<li><span class='txt'>item-7</span> <span class='mOrder'>7</span></li>
<li><span class='txt'>item-8</span> <span class='mOrder'>8</span></li>
<li><span class='txt'>item-9</span> <span class='mOrder'>9</span></li>
</ul>
<input type='button' id='btnSave' value=' Save order ' />
sorted through jquery sortable plugin
$(".items").sortable({
$(".items li").each(function () {
var OrderNum = (parseInt($(this).index()) + 1);
$(".mOrder", this).html(OrderNum);
});
});
now I want to save new order
I have saveOrder.ashx file to update records in database
I have problem while sending data in ajax
I am trying as below
$("#btnSave").click(function(){
var arr=[];
$(".items li").each(function () {
arr.push({'m'+$(this).index():$(".txt",this).html()});
//m0:item1, m1:item2,....
});
$.ajax({
url:'',
data:arr;//here is problem
});
});
I am sending this but it is not accessable in saveOrder.ashx
I can try any alternative

I may have 2 answers:
wrap the array in a JSON object:
url:'',
data: {'arrayofObjects':arr}
JSON.stringify()
url:'',
data: JSON.stringify(arr)
ADDITIONAL:
JSON.stringify() + JSON object wrap
url:'',
data: JSON.stringify({arrayofObjects:arr})

Related

c# get data of json script

I want to get some data of a homepage but the wanted value is in a json script. How do I get the value?
example:
<div id="contentWrap">
<div id="contentTextWrap">
<div id="contentText">
<h1>Tiefgarage Alte Oper</h1>
<div class="parkhaus-detail-freespaces">
<h4>Freie Parkplätze: <span class="parkhaus-detail-freespaces-value"></span></h4>
<em class="parkhaus-detail-freespaces-date-time"></em>
<br>
<br>
</div>
(... later on the html script...)
<script>
$.getJSON('/_extern/mdm_import/PBG/_extern/mdm_import/2781002/18944.json', function(data) {
$('.parkhaus-detail-freespaces-value').html(data['freespaces']);
var m = moment(data['parking_facility_status_time']);
$('.parkhaus-detail-freespaces-date-time').html('Stand vom '+m.format('DD.MM.YYYY')+' um '+m.format('HH:mm'));
$('.parkhaus-detail-freespaces').css('display', 'block');
});
</script>
In c# I download the html-string with the webcliend, but how do I get access to the value "parkhaus-detail-freespaces-value"?
Use JSON.parse() to convert the JSON to an object, then use the object's properties
var artikel = JSON.parse(data);
$('.parkhaus-detail-freespaces-value').html(artikel.freespac‌​es);

How to append a C# formatted html

I have a button that append's the same layout of html but I have a problem taking the select values with it. My html is:
<div id="degreePlusSign">Button</div>
<div class="padding">
<div class="col-md-5 col-xs-12">
<label for="prefix" class="sr-only">Degrees</label>
<select class="form-control marginBottom15">
#{
foreach (var degree in ViewBag.NewDegrees)
{
<option value="#degree.DegreeID" selected>#degree.DegreeName</option>
}
}
</select>
<span class="glyphicon form-control-feedback"></span>
</div>
</div>
JS:
$('#degreePlusSign').on('click', function () {
$(this).closest('.padding').append('<div class="padding mBottom"><i class="fa fa-times-circle fa-2x" aria-hidden="true"></i><div class="col-md-5 col-xs-12"><select class="form-control marginBottom15">#{foreach (var degree in ViewBag.NewDegrees){<option value="#degree.DegreeID" selected>#degree.DegreeName</option>}}</select><span class="glyphicon form-control-feedback"></span></div><div class="col-md-7 col-xs-12"><input class="form-control" placeholder="Major/Area of Study" type="text" /></div></div>');
});
Basically it recreates the html, but my problem is I'm using a foreach loop to bring in the values from the backend and it will only work with the inital container, not the duplicated containers afterwards. How do I keep the values on every duplication with the append jquery?
You have got two options:
Spit options values (formatted) from C# and keep in a JS variable:
{
var opts=new StringBuilder();
var sel="selected";
foreach(var d in ViewBag.NewDegrees)
{
opts.Append($"{d.DegreeName}");
sel="";
}
}
Then somewhere down store it into a js variable:
var optsList="#(opts)";
Now you can use append new HTML as:
$('#degreePlusSign').on('click', function () {
$(this).closest('.padding').append('<div class="padding mBottom"><i class="fa fa-times-circle fa-2x" aria-hidden="true"></i><div class="col-md-5 col-xs-12"><select class="form-control marginBottom15">'+
optsList/*THIS IS THE VALUE WE STORED FROM C# CODE*/
+'</select><span class="glyphicon form-control-feedback"></span></div><div class="col-md-7 col-xs-12"><input class="form-control" placeholder="Major/Area of Study" type="text" /></div></div>');
});
Clone the generated select element and use that:
$('#degreePlusSign').on('click', function () {
/*CLONE EXISTING SELECT ELEMENT. YOU MAY WANT TO PUT AN ID FOR SELECTION*/
var cl=$("select.form-control.marginBottom15").clone();
var d = $("").addClass("padding mBottom")
append("").addClass("fa fa-times-circle fa-2x").attr("aria-hidden",'true');
/*APPEND CLONED SELECT TO INNER DIV*/
d.append("").addClass("col-md-5 col-xs-12").append(cl);
d.append(cl);
d.append("").addClass(glyphicon form-control-feedback");
d.append("").addClass("col-md-7 col-xs-12").append("").addClass("form-control")
.attr("placeholder","Major/Area of Study").attr("type","text");
$(this).closest(".padding").append(d);
});`
Hope you will be able fix any jQuery mess. I haven't used it since long.
.clone was what I was looking for. $('.padding').clone().append('.padding');

Using Angular 2 to return HTML from C#/.NET service

I have an existing .NET application that I want to update to use an Angular 2 front-end. There is a section of a page that has dynamic content and every time I want to get the most up-to-date content, I currently use jquery similar to this:
$.get("/Plan/Variety/VarietyList")
.done(function (data) {
PlaceReturnedData($("body"), data, "variety-list-selling");
});
The data returned is the exact HTML I need, no need to manipulate it.
How can I use Angular 2 to return this same data? I've looked around and only see how to handle JSON data, such as the example below from Angular 2's Tour of Heroes tutorial:
heroes.component.ts:
heroes: Hero[];
selectedHero: Hero;
constructor(
private router: Router,
private heroService: HeroService
) { }
getHeroes(): void {
this.heroService.getHeroes().then(heroes => this.heroes = heroes);
}
ngOnInit(): void {
console.log('initializing MenuVarietiesComponent');
this.getHeroes();
}
hero.service.ts
#Injectable()
export class HeroService {
private heroesUrl = 'app/heroes'; // URL to web api
private headers = new Headers({'Content-Type': 'application/json'});
constructor(private http: Http){ }
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
}
heroes.component.html:
<ul class="heroes">
<!-- On click, execute onSelect() function and pass in the hero variable from the ngFor. Apply the "selected" class if hero & selectedHero match, remove it if they don't -->
<li *ngFor="let hero of heroes"
(click)="onSelect(hero)"
[class.selected]="hero === selectedHero">
<span class="badge">{{hero.id}}</span>
<span>{{hero.name}}</span>
<!-- We need to stop propagation so we don't trigger the onSelect() method on the <li> -->
<button class="delete" (click)="delete(hero); $event.stopPropagation()">x</button>
</li>
</ul>
How can I modify the example Angular 2 code above to handle HTML data rather than JSON data so I can take advantage of code I already have set up on the C# end? I'm guessing the *ngFor in the html is irrelevant since I probably won't need to save my data as an array and I would probably need to change the value of heroesUrl to /Plan/Variety/VarietyList, but I'm a little stuck after that.
EDIT:
Here is what the returned HTML from my controller might look like:
<div class="varietyTypeName" data-toggle="collapse" data-target="" aria-expanded="true" aria-controls="">
Greens
<i class="fa fa-angle-down arrow-toggle"></i>
</div>
<div class="collapse in collapsableArea">
<div class="varietyFamilyName">Arugula</div>
<div class="varietyName">
<a class="ajax-rep rep-main-col" href="/Plan/Selling/DetailsPPVS/5409">Astro</a>
<a href="#deleteVarietySelling" id="deleteVarietySelling_5409" class="quick-delete fa-minus-button" title="Delete" data-toggle="modal">
<i class="fa fa-minus"></i>
</a>
</div>
</div>
<div class="collapse in collapsableArea">
<div class="varietyFamilyName">Kale</div>
<div class="varietyName">
<a class="ajax-rep rep-main-col" href="/Plan/Selling/DetailsPPVS/3720">Kalettes</a>
<a href="#deleteVarietySelling" id="deleteVarietySelling_3720" class="quick-delete fa-minus-button" title="Delete" data-toggle="modal">
<i class="fa fa-minus"></i>
</a>
</div>
</div>
What you need to do is something like this:
import {Component, OnInit} from '#angular/core';
import {DomSanitizationService} from "#angular/platform-browser";
export class SideBarComponent implements OnInit {
myHTML;
constructor(private sanitizer: DomSanitizationService, private myService : MyHTTPService){
myService.getHTMLFromBackend().subscribe(
data => {
this.myHTML = this.sanitizer.bypassSecurityTrustHtml(data.content)
});
}
ngOnInit() {}
}
Then when you are trying to use it in the html (DOM) Just simply do
{{myHTML}}

Building HTML dynamically with knockout

I have a single-page-application in MVC4 project in C#.
In my HTML I have a like-a-table lists - first is the table titles, and second is in a div with a "foreach" property (knockout) and presents all the items in my list.
Now, I need this "table" to be dynamic - I'll get a list of columns and "instructions" (column title, column class name, column value name, css conditions, etc.) and the HTML will be built dynamically.
Is it possible with knockout?
This is my code now. There are only 5 columns. I need it to be dynamic so I can easily add (and remove) columns by changing the instruction list, whithout touching the HTML.
<ul class="assetsTitles">
<li class="ItemKey" data-bind="click: sortBy.bind($data, 'Key'), css: { selected: Filter().OrderBy() == 'Key', desc: Filter().Descending() }"><span>Key</span></li>
<li class="ItemName" data-bind="click: sortBy.bind($data, 'Name'), css: { selected: Filter().OrderBy() == 'Name', desc: Filter().Descending() }"><span>Item Name</span></li>
<li class="ItemProp1" data-bind="click: sortBy.bind($data, 'ItemProp1'), css: { selected: Filter().OrderBy() == 'ItemProp1', desc: Filter().Descending() }">ItemProp1</li>
<li class="ItemProp2" data-bind="click: sortBy.bind($data, 'ItemProp2'), css: { selected: Filter().OrderBy() == 'ItemProp2', desc: Filter().Descending() }">ItemProp2</li>
<li class="ItemProp3" data-bind="click: sortBy.bind($data, 'ItemProp3'), css: { selected: Filter().OrderBy() == 'ItemProp3', desc: Filter().Descending() }">ItemProp3</li>
</ul>
<div data-bind="foreach: items, visible: items().length > 0">
<div class="itemRow" data-bind=" attr: { id: RowId() }">
<ul class="itemRowDetails " data-bind="visible: ShowDetails, selected: IsSelected, click: $parent.showItemDetails.bind($data, $data, $parent.type), css: { selected: IsSelected() }">
<li class="ItemKey" data-bind=" title: Key"><span data-bind="text: Key" /></li>
<li class="ItemName" data-bind=" title: Name"><span data-bind="text: Name" /></li>
<li class="ItemProp1" data-bind=" title: ItemProp1"><span data-bind="text: ItemProp1" /></li>
<li class="ItemProp2" data-bind=" title: ItemProp2"><span data-bind="text: ItemProp2" /></li>
<li class="ItemProp3" data-bind=" title: ItemProp3Display"><span data-bind="text: ItemProp3Display, css: { alertDetail: ItemProp3Alert, alertDetail2: ItemProp3Alert2 }" /></li>
</ul>
</div>
</div>
you can use ko.renderTemplate
and doing some thing like :
<!-- ko foreach:$root.visibleColumns() -->\
<li data-bind=\"attr:{'data-columnname' : columnName}\" role=\"column\" ><span data-bind=\"attr:{'class': columnHeaderCss, 'data-columnname' : columnName,'data-headertext': headerText}, text: headerText\"></span> </li>\
<!-- /ko -->\
and pass the columns list to viewModel :
ko.dataGrid = {
viewModel: function (configuration) {
var me = this;
$.extend(me, {
columns: configuration.columns,
visibleColumns: function () {
var res = [];
$.each(me.columns, function (i, c) {
if (c.visible)
res.push(c);
});
return res;
},
});
}
You could try building the html in script using traditional techniques then attach it to an element. Then to add this to the binding the name of that element needs to be included as a 2nd parameter:
ko.applyBindings(viewModel, dynamicElement)
Alternatively ko has html ("html:") and text binding ("text:") options.
In constructing the html in code you may need to use the "containerless control flow syntax" i.e. wrap within the comment notation e.g. <!-- ko foreach: myItems --> .... <!-- /ko --> Where myItems is an array.
Usual caveats apply regarding possible injection attacks!
Its been some time since I played with ko..

Dynamically add multiple carousel jquery sliders on a cshtml page

I would like to add multiple jquery sliders on a cshtml page using data from a database. Basically I have a collection of tabs that when active dynamically populate a slider contained within with data from a database.
cshtml code with Razor C# hooks:
<div class="tabbable">
<ul id="myTab" class="nav nav-tabs">
#foreach(var row in db.Query(queryCategory))
{
<li>#row.Food_Category</li>
}
</ul>
<div class="tab-content">
#{bool first = true;}
#foreach(var row in db.Query(queryCategory))
{
var ids= #row.Food_Category;
<div class="#{if (first){<text>tab-pane active</text> first = false;}else{<text>tab-pane</text>}}" id=#ids>
<p>I'm in #row.Food_Category.</p>
<div class="list_carousel">
<ul id="foo">
#foreach(var row1 in db.Query("SELECT * FROM Food WHERE Food_Category = #0", ids))
{
<li>#row1.Food_ID</li>
}
</ul>
<div class="clearfix"></div>
<a id="prev2" class="prev" href="#"><</a>
<a id="next2" class="next" href="#">></a>
<div id="pager2" class="pager"></div>
</div>
</div>
}
</div>
</div><!--tabbable-->
The bit I think needs focus:
The rest of the code is dynamic except this bit. I'm not sure how to go about getting a unique id for each un-ordered list (e.g foo1, foo2, foo3 dynamically) depending on the number of items in a database column.
<ul id="foo">
#foreach(var row1 in db.Query("SELECT * FROM Food WHERE Food_Category = #0", ids))
{
<li>#row1.Food_ID</li>
}
</ul>
The Jquery bit:
Here Im not sure, but I think I'll need to set this options true for a range of #id specified dynamically.
<script>
//Carousel
$('#foo').carouFredSel({
width: '100%',
scroll: 2,
auto: false,
prev: '#prev2',
next: '#next2',
pagination: "#pager2",
mousewheel: true,
swipe: {onTouch: true}
});
</script>
I'm just starting out with webmatrix & jquery please bear with me. Thanks
If you just want to get the unique ID for each unorder list you can do somethink like this
#int inc=0;
#foreach(var row in db.Query(queryCategory))
{
var ids= #row.Food_Category;
<div class="#{if (first){<text>tab-pane active</text> first = false;}else{<text>tab-pane</text>}}" id=#ids>
<p>I'm in #row.Food_Category.</p>
<div class="list_carousel">
<ul id="foo#inc++">
#foreach(var row1 in db.Query("SELECT * FROM Food WHERE Food_Category = #0", ids))
{
<li>#row1.Food_ID</li>
}
</ul>
<div class="clearfix"></div>
<a id="prev2" class="prev" href="#"><</a>
<a id="next2" class="next" href="#">></a>
<div id="pager2" class="pager"></div>
</div>
</div>
}
but if you just want to get carousal dynamically for-each under list you can use for each function in jquery foreach
$('ul').each(function(index) {
$('this').carouFredSel({
width: '100%',
scroll: 2,
auto: false,
prev: '#prev2',
next: '#next2',
pagination: "#pager2",
mousewheel: true,
swipe: {onTouch: true}
});
});

Categories

Resources