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.freespaces);
Related
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');
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}}
I have a code in C# where I want to extract the below value (the text "I want this text" in the HTML code below). I have reformat the HTML code to make it easily readable.
<div class="paste-copy-url" style="margin:0 0 0 0;">
<h4>My Stats:</h4>
<div class="line">
<div class="wrap-input">
<input onclick="this.select();" value="I want this text" readonly="readonly">
</div>
</div>
<h4>Website Link:</h4>
<div class="line">
<div class="wrap-input"><input onclick="this.select();" value="Some value" readonly="readonly">
</div>
</div>
</div>
The code I tried (It is giving me the text : "Website Link:"):
var myvaluetoextract = htmlDocument.DocumentNode.SelectSingleNode("//div[#class='paste-copy-url']");
What am I doing wrong? Can I use this approach to get that element (There is only 1 instance of the div class in the page)?
var input = htmlDocument.DocumentNode
.SelectSingleNode("//div[#class='paste-copy-url']//div[#class='wrap-input']/input");
var yourText = input.Attributes["value"].Value;
You can do it like this:
var myvaluetoextract = htmlDocument.DocumentNode.SelectSingleNode("//div[#class='paste-copy-url']//input");
var value = myvaluetoextract.GetAttributeValue("value", null);
//input means you search for input elements in the div's subtree, recursively. GetAttributeValue is a helper that will never fail, even if the attribute doesn't exists (in this case if will return the 2nd passed parameter - which is null here)
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})
I have a form that you enter data into and it performs a calculation on it and give an answer. what i want to do is for it to keep the data in the form so that you can quickly repost so that you don't have to change all the data. but I cant keep coming up with the error of it not existing, which I suppose is correct until the form has been posted!
#{
var total = 0m;
var totalMessage = "";
if (IsPost)
{
var age = Request["frmage"].AsInt(0);
var weight = Request["frmweight"].AsDecimal();
var SerCre = Request["frmSerCre"].AsDecimal();
var sexfactor = Request["frmGender"]== "M" ? 1.23m : 1.04m;
total =Convert.ToDecimal ((((140 - age)*weight)* sexfactor )/SerCre ) ;
totalMessage = total.ToString("0.00") + "(ml/min) ";
}
}
<div class="memberRegistration">
<form method="post">
<p>
<label class="formLabel">Age:</label> in years
<input class="formTextField" type="text" name="frmAge" size="3" value="#age"/>
</p>
<p>
<label class="formLabel">Weight:</label> in Kg (1st = 6.35kg)
<input class="formTextField" type="text" name="frmWeight" value="#weight"/>
</p>
<p>
<label class="formLabel">Serum Creatinine:</label> in μmol/L
<input class="formTextField" type="text" name="frmSerCre" value="#SerCre"/>
</p>
<p>
<label class="fieldLabel">Gender:</label>
<select name="frmGender" id="select" value="#sexfactor">
<option value="M">Male</option>
<option value="F">Female</option>
</select>
</p>
<p><input type="submit" value="Calculate" /></p>
</form>
<p>Calculated creatinine clearance <b>#totalMessage</b></p>
</div>
Try this
var age = 0;
if (IsPost)
{
age = Request["frmage"].AsInt(0);
}
<input class="formTextField" type="text" name="frmAge" size="3" value="#age"/>
But normally it would be better to use a model to hold your values, then in your controller you pass those values back again to your form
Enable the ViewState of the page and controls and also use aspx control, not HTML.
I don't thing that i realy understand the Question because the default thing is that the web page keeps it's view state so the data will still be the same after the post back but here's the solution :
you can simply use ASP Controls because it keep it's view state
or you can give each control of them it's value in the C# , you can assign to each control it's value back
Hope I Helped
Since you are using ASP.NET MVC Razor, what you can do is, do not submit the form using <input type="submit" value="Calculate" /> , instead change it to a simple button like
<input type="button" value="Calculate" onclick="javascript:Submitform();" />
and submit the form using Jquery POST.e.g. like below
function SubmitForm(){
var formData = $("form").serialize() ;
var submitUrl = 'yourURL' ;
$.ajax({
type : 'POST' ,
url : submitUrl ,
data : formData ,
success : function (data ){ alert ("Request successful") ;}
error : function (jqXHR, status , errorthrown) { alert ("error Occured");}
});
}