How to read JSON and Display in html table in c#? - c#

I have following JSON:
{"ios_info":{"serialNumber":"F2LLMBNJFFFQ1","imeiNumber":"0138840041323551","meid":"","iccID":"89014104276400960452","firstUnbrickDate":"11\/27\/13","lastUnbrickDate":"11\/27\/13","unbricked":"true","unlocked":"false","productVersion":"7.1.2","initialActivationPolicyID":"23","initialActivationPolicyDetails":"US AT&T Puerto Rico and US Virgin Islands Activation Policy","appliedActivationPolicyID":"23","appliedActivationDetails":"US AT&T Puerto Rico and US Virgin Islands Activation Policy","nextTetherPolicyID":"23","nextTetherPolicyDetails":"US AT&T Puerto Rico and US Virgin Islands Activation Policy","macAddress":"ACFDEC6C988A","bluetoothMacAddress":"AC:FD:EC:6C:98:8B","partDescription":"IPHONE 5S SPACE GRAY 64GB-USA"},"fmi":{"#attributes":{"version":"1","deviceCount":"1"},"fmipLockStatusDevice":{"#attributes":{"serial":"F2LLMBNJFFFQ","imei":"013884004132355","isLocked":"true","isLost":"false"}}},"product_info":{"serialNumber":"F2LLMBNJFFFQ1","warrantyStatus":"Apple Limited Warranty","coverageEndDate":"11\/25\/14","coverageStartDate":"11\/26\/13","daysRemaining":"497","estimatedPurchaseDate":"11\/26\/13","purchaseCountry":"United States","registrationDate":"11\/26\/13","imageURL":"http:\/\/service.info.apple.com\/parts\/service_parts\/na.gif","explodedViewURL":"http:\/\/service.info.apple.com\/manuals-ssol.html","manualURL":"http:\/\/service.info.apple.com\/manuals-ssol.html","productDescription":"iPhone 5S","configDescription":"IPHONE 5S GRAY 64GB GSM","slaGroupDescription":"","contractCoverageEndDate":"11\/25\/15","contractCoverageStartDate":"11\/26\/13","contractType":"C1","laborCovered":"Y","limitedWarranty":"Y","partCovered":"Y","notes":"Covered by AppleCare+ - Incidents Available","acPlusFlag":"Y","consumerLawInfo":{"serviceType":"","popMandatory":"","allowedPartType":""}}}
Reading JSON string:
private string GetKeyValuePairs(string jsonString)
{
rowcnt++;
var resDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString);
string sdict = string.Empty;/*#"<table id='tblAppleResult' cellspacing='0' cellpadding='3' border='1' style='width: 100%; border-collapse: collapse;'>
<tr>
<td>
</td>
<td>
</td>
</tr>";*/
foreach (string key in resDict.Keys)
{
sdict += "<br/> " + key + " : " + (resDict[key].GetType() == typeof(Newtonsoft.Json.Linq.JObject) ? GetKeyValuePairs(resDict[key].ToString()) : resDict[key].ToString());
//sdict += "<tr><td> " + key + "</td> " + (resDict[key].GetType() == typeof(Newtonsoft.Json.Linq.JObject) ? "<td>" + GetKeyValuePairs(resDict[key].ToString()) + "</td></tr>" : "<td>" + resDict[key].ToString() + "</td></tr>");
}
//sdict += "</table>";
return sdict;
}
This displays the Data. But i want in HTML Table Format.(independent of inner Keys. i mean every row will began in new as per commented above.
Problem:
As its recursive it goes on displaying table into another table. i.e for child attributes with other child attributes.
I need the output just in TWO COLUMNS ONLY with Key:Value as output.

Here is the solution:
string tbl = #"<table id='tblAppleResult' cellspacing='0' cellpadding='3' border='1' style='width: 100%; border-collapse: collapse;'><tr>
<td>
</td>
<td>
</td>
</tr>";
lblkeyValue.Text = tbl+GetKeyValuePairs(responseText)+"</table>";

Related

Create HTML table row dynamically with c#

I want to add a row in HTML table with C# method, I have written the code but after execution the row appears at the top of the page not under HTML table.
<tr>
<th></th>
<th>ID</th>
<th>Date</th>
<th>Plot No.</th>
<th>Area</th>
<th>Location</th>
<th>Phase/Division</th>
<th>Remarks</th>
<th>Documents</th>
</tr>
public void AddRow() {
string html = "<tr>" +
"</td> <td class=\"text-right\"><a href = \"javascript:void(0)\" ><i class=\"fa fa-pencil\" ></i></a> </td>" +
"<td><p>1</p></td>" +
"<td><input type = \"date\" runat=\"server\" style=\"width:140px\" /></td>" +
"<td><input type =\"text\" runat=\"serve\"' style=\"width:100px\" /></td><td>" +
"<input type = \"text\" runat=\"server\" style=\"width:100px\"/></td>" +
"<td><input type = \"text\" Value=\"Test2\" runat=\"server\"/></td>" +
"<td><input type = \"text\" runat=\"server\" style=\"width:100px\"/></td>" +
"<td><input type = \"text\" runat=\"server\" style=\"height:50px\"/></td><td>" +
"<input type = \"file\" runat=\"server\" style=\"height:50px\"/></td></tr>";
Response.Write(html);
}
and calling this function from <a> tag in the table.
<td>
<a href="#" runat="server" onserverclick="Unnamed_ServerClick">
<i class="fa fa-pencil" runat="server"></i>
</a>
</td>
and it appears on the top like this.Result
Take a look on the TagBuilder:
https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/views/using-the-tagbuilder-class-to-build-html-helpers-cs

How to remove enter in css

I'm working on something but i'd like to know how to stop text from auto entering.
I don't use a break there so I don't really know what the problem is. I used something from overstack to show a div when you hover on it. Maybe this need's to be centered because the div wouldn't have the right position. I don't really know I'm pretty new to CSS.
My code looks like this:
C#
public string ToonGrenzenPerZoekwoord(string zoekwoord)
{
string list = "";/*"<h1> Resultaten via grenzen </h1> <br>";*/
foreach (DataTable table in _persistcode.SearchGrenzenByKeyword("%" + zoekwoord + "%").Tables)
{
foreach (DataRow row in table.Rows)
{
list += "<span class='t1'>" + row["Grens"].ToString() + ": <br>" + "</span>" + "<span class='t2'>" + row["Sanctie"].ToString() + "<br> <br>" + "Dit hoort thuis in de categorie: " + row["IDCategorieën"].ToString() + "</span>" + "<br>";
}
}
return list;
}
HTML & CSS
.infospan{
background: none repeat scroll 0 0 #F8F8F8;
border: 5px solid #DFDFDF;
color: #717171;
font-size: 13px;
height: 30px;
letter-spacing: 1px;
line-height: 30px;
margin: 0 auto;
position: relative;
text-align: center;
text-transform: uppercase;
top: -80px;
display:none;
padding:0 20px;
}
.infospan::after{
content:'';
position:absolute;
bottom:-10px;
width:10px;
height:10px;
border-bottom:5px solid #dfdfdf;
border-right:5px solid #dfdfdf;
background:#f8f8f8;
left:50%;
margin-left:-5px;
-moz-transform:rotate(45deg);
-webkit-transform:rotate(45deg);
transform:rotate(45deg);
}
p{
cursor:pointer;
}
p:hover span{
display:block;
}
<!--Resultaat-->
<div id="resultaat" runat="server" style="text-align: center; color: white; font-size: 24px;"></div>
I don't know about the css trick but i think this simple javascript code will help you :
$('your_class').bind('keypress', function(e){
if(e.keyCode == 13){
return false;
}
});
If you mean white space beneath your list items you should be careful with the <br>'s
Although I don't support the use of <br> in general, (see Is it sometimes bad to use <BR />?) you might want to try this:
public string ToonGrenzenPerZoekwoord(string zoekwoord)
{
string list = "";/*"<h1> Resultaten via grenzen </h1> <br>";*/
foreach (DataTable table in _persistcode.SearchGrenzenByKeyword("%" + zoekwoord + "%").Tables)
{
foreach (DataRow row in table.Rows)
{
list += "<p class='t1'>"; //using paragraph
list += row["Grens"].ToString();
list += ": <br>" + "</span>" + "<span class='t2'>";
list += row["Sanctie"].ToString() + "<br> <br>";
list += "Dit hoort thuis in de categorie: ";
list += row["IDCategorieën"].ToString();
list += "</p>"; //ommited final <br>
}
}
return list;
}
It might be even better to rule out all br's, but I'll need to be sure what your exact question is.
Side note: please be advised if somehow in your data, e.g.: row["Sanctie"] a value of
<script>alert('turtle`);</script>
is present, you'll find yourself having a hard time to 'shoo it away'.

Sending my parameters to the other side

Sorry if there are typos or inc clay error when I'm incredibly bad at English.
It is such that I need to send some value over the epay to receive my payment on my website.
onto hh.aspx looks like this:
<asp:Literal ID="LiteralDKK" runat="server"></asp:Literal>
<asp:Literal ID="LiteralPris" runat="server"></asp:Literal>
<asp:Literal ID="Literalwindowstate" runat="server"></asp:Literal>
<asp:Literal ID="LiteralOrderid" runat="server"></asp:Literal>
<asp:Literal ID="Literalmerchantnumber" runat="server"></asp:Literal>
on hh.aspx.cs
string dkk = "DKK";
string windowstate = "3";
string merchantnumber = "1111111";
string prisen = "10";
string ordernr = "159sg";
LiteralDKK.Text = "<input id=\"HiddenPris\" type=\"hidden\" name=\"currency\" value=\"" + dkk + "\" />";
Literalmerchantnumber.Text = "<input id=\"Hiddenmerchantnumber\" type=\"hidden\" name=\"merchantnumber\" value=\"" + merchantnumber + "\" />";
Literalwindowstate.Text = "<input id=\"Hiddenwindowstate\" type=\"hidden\" name=\"windowstate\" value=\"" + windowstate + "\" />";
LiteralPris.Text = "<input id=\"HiddenPris\" type=\"hidden\" name=\"amount\" value=\"" + prisen + "\" />";
LiteralOrderid.Text = "<input id=\"HiddenOrderid\" type=\"hidden\" name=\"orderid\" value=\"" + ordernr + "\" />";
//It must send my value onto this here page
Response.Redirect("https://ssl.ditonlinebetalingssystem.dk/integration/ewindow/Default.aspx");
My parameters which I would like to have sent to you can see how to appear here
If I had to do it in html, it looked like this,
<form action="https://ssl.ditonlinebetalingssystem.dk/integration/ewindow/Default.aspx" method="post">
<input name="merchantnumber" value="ENTER YOUR MERCHANT NUMBER HERE">
<input name="amount" value="10495"> <input name="currency" value="DKK">
<input name="windowstate" value="3"> <input type="submit" value=
"Go to payment">
</form>
The reason I do not do it is to secure me the right price and ordernr and many other things which must cross in.
The documentation here seems to provide simple ways to do this:
http://tech.epay.dk/da/betalingsvindue-integration
In English:
http://tech.epay.dk/en/payment-window-integration

posting data from a razor generated table

I have a table filled with generated data using razor. Each row has the id of the PlanID in the database.
<tbody>
#foreach(var plan in ViewBag.plans) {
<tr id="#plan.PlanID">
<td contenteditable="true">#plan.Name</td>
<td contenteditable="true">#plan.Code</td>
<td contenteditable="true">#plan.Description</td>
<td contenteditable="true">#plan.DataAmount</td>
<td contenteditable="true">#plan.Price</td>
<td contenteditable="true">#plan.SmartPhoneCost</td>
<td><a><span class="glyphicon glyphicon-pencil"></span></a></td>
</tr>
}
</tbody>
I have also made button click append the table with a new row to add a plan
function Add() {
$("#tableData tbody").append(
"<tr role='form' action='/api/wirelessplans' method='post'>" +
"<td><input name='Name' type='text' size='30' maxlength='30'/></td>" +
"<td><input name='Code' type='text' /></td>" +
"<td><input name='Description' type='text' size='50' maxlength='50'/></td>" +
"<td><input name='DataAmount' type='text' /></td>" +
"<td><input name='Price' type='text' /></td>" +
"<td><input name='SmartPhoneCost' type='text' /></td>" +
"<td><a class='save' type='submit'><span class='glyphicon glyphicon-ok'></span></a></td>" +
"</tr>")
};
$(function () {
$("body").on("click", ".addPlan", function () {
Add()
});
});
I have made the the td's editable and would like to click on the icon to submit the changes to -- api/wirelessplans/ that I defined in my controller. How do I grab only the values that are changed (or added in the new row) and post/put to the database?

"inserting the dynamically generated rows into the table"

I am bit new in the c# programming, so I got stuck at one place. Need your help.
Actually through javascript I am generating table(4 columns) rows(having textboxes so that user can give inputs) as per as the user button click. As the number of rows are not fixed and we dont have the exact name of the textboxes so now my problem is how should we insert these rows into the sqlserver table?
should I use simply the loop for generating the name of the Textboxes for every user button click? and once we got the name for all controls can we insert these all through a single insert statement by using loop?
warm regrads,
ammy
If you're using just a regular html table add 'runat="server"' Tag with JS as well as html form controls then just change TableRow to HtmlTableRow and TextBox to HtmlInputText. All of those controls are in the System.Web.UI.HtmlControls namespace.
Assuming you're using the Table server control then it's just:
foreach (TableRow row in table.Rows)
{
var col2 = (TextBox)row.Cells[1].Controls[0];
//Do DB inserting stuff here With col2
string stringToInsert= col2 .Text;
}
I'm asuming you're using MVC..
You can start by creating a model such as:
public class YourModel
{
public IEnumerable<Users> users { get; set; }
}
Than create a view and add the rows dynamically by script given below:
<script type="text/javascript">
var Rows = 1;
// We already got the 0 element as html so start from 1
function AddUser() {
$("#UserTable").append('<tr>' +
'<td><input type="text" name="users[' + Rows + '].Name" style="width:100px;" /></td>' +
'<td><input type="text" name="users[' + Rows + '].Surname" style="width:100px;" /></td>' +
'<td><input type="text" name="users[' + Rows + '].Age" style="width:50px;" /></td>' +
'<td><input type="text" name="users[' + Rows + '].Date" style="width:70px;" /></td>' +
'</tr>');
// Add datepicker (this is an optional jQueryUI stuff)
$('input[name="users[' + Rows + '].Date"]').datepicker({ dateFormat: 'yy.mm.dd' });
// Go to next row
Rows = Rows + 1;
}
$(document).ready(function(){
// Create an empty row on load
AddUser();
// Than on each click add another row
$('input[type=button]').click(function(){ AddUser(); });
});
</script>
<div>
<table id="UserTable">
<tr>
<td><input type="text" name="user[0].Name" style="width:100px;" value="Berker" /></td>
<td><input type="text" name="user[0].Surname" style="width:100px;" value="Yüceer" /></td>
<td><input type="text" name="user[0].Age" style="width:50px;" value="24" /></td>
<td><input type="text" name="user[0].Date" style="width:70px;" value="2012.12.11" /></td>
</tr>
</table>
<input type="button" id="add" value="Add" />
</div>
fiddle for the script: http://jsfiddle.net/BerkerYuceer/YFecD/
From your controller you can get the values as show below:
// Thanks to LinqToSql you can define ur Sql-DB this way
YourDBDataContext db = new YourDBDataContext();
//
// POST: /YourForm/Edit
[HttpPost]
public ActionResult Edit(YourModel model)
{
try
{
// if users not empty..
if (model.users != null)
{
// Each User in Users
foreach (var user in model.users)
{ // Save it to your Sql-DB
db.Users.InsertOnSubmit(user);
db.SubmitChanges();
}
}
// Return
return RedirectToAction("Index");
}
catch (Exception ex)
{
return RedirectToAction("Error", new { ErrorMessage = "Message[" + ex.Message + "] - Source[" + ex.Source + "] - StackTrace[" + ex.StackTrace + "] - Data[" + ex.Data + "]" });
}
}
//
// GET: /YourForm/Error
public ActionResult Error(String ErrorMessage)
{
ViewData["Error"] = ErrorMessage;
return View();
}
simple as this!

Categories