How to convert a struct xaml grid wpf to json array - c#

I am using a xaml wpf grid. I want to convert struct the grid to json. Do you have any ideas on how?
Please see this example:
<GridBinding>
<Grid ID="grd1" ES="9" KFN="" PFN="" GN="گرید 1">
<Column ID="ID" SystemId="517" TableId="3082" FieldId="1" Properties="Header=ID,Visible=True,VisibleIndex=4,GroupIndex=-1,ReadOnly=True,SortIndex=1,SortOrder=Descending,Mask=0,Width=ناعدد," IsCondition="False" IsForce="False" VS="True" ISFormulla="False" VF="1" ReadOnly="True" />
<Column ID="Name" SystemId="517" TableId="3082" FieldId="2" Properties="Header=Name,Visible=True,VisibleIndex=1,GroupIndex=-1,ReadOnly=False,SortIndex=2,SortOrder=Ascending,Mask=0,Width=ناعدد," IsCondition="False" IsForce="False" VS="True" ISFormulla="False" VF="2" ReadOnly="False" />
<Column ID="Family" SystemId="517" TableId="3082" FieldId="3" Properties="Header=Family,Visible=True,VisibleIndex=2,GroupIndex=-1,ReadOnly=False,SortIndex=-1,SortOrder=None,Mask=1,Width=ناعدد," IsCondition="False" IsForce="False" VS="True" ISFormulla="False" VF="3" ReadOnly="False" />
<Column ID="Avg" SystemId="517" TableId="3082" FieldId="10" Properties="Header=Avg,Visible=True,VisibleIndex=3,GroupIndex=-1,ReadOnly=False,SortIndex=-1,SortOrder=None,Mask=0,Width=ناعدد," IsCondition="False" IsForce="False" VS="True" ISFormulla="False" VF="4" ReadOnly="False" />
<Column ID="ردیف" SystemId="0" TableId="0" FieldId="-1" Properties="Header=ردیف,Visible=True,VisibleIndex=0,GroupIndex=-1,ReadOnly=False,SortIndex=-1,SortOrder=None,Mask=0,Fixed=Left,Width=ناعدد," IsCondition="False" IsForce="False" VS="False" ISFormulla="False" VF="0" ReadOnly="False" />
</Grid>
</GridBinding>
I want this result:
var object = {
"grd1": [ {
ID: "ID",
Visible: "True",
FieldId: "1",
IsForce: "false",
ReadOnly="true"
} ],
};
This is my code:
if ((item as XmlElement).Attributes["Type"].Value == "Grid") {
if (Id_elem == (itemgrigIn as XmlElement).Attributes["ID"].Value) {
if (Orientation == "Horizontal" || Orientation == "" || Orientation == null) {
s += " <div id=" + Id_elem + "myDiv" +
" dir='rtl' align='center' class='table-responsive'></div> " +
" <script> $(document).ready(function() {var " +
Id_elem + "Divresult = $(" + "'" + "<div id=" +
Id_elem + "Div" + " ></div>);" +
"'" + " $(" + Id_elem + "Div" + ").append(" +
Id_elem + "Divresult); var " +
Id_elem + " = new grid(" + "'" + Id_elem + "'" +
"," + countgrid + ");" + Id_elem +
".init(); }); </script> ";
}
}
}

It is not trivial task. If you want make all right You must first create a parser from xaml string to object. And then parser from object to json string. You must research and find libs to convert xml and json.

hi iam sloved this problem
1- first use XmlNode
public string CreateHtml(Form formInfo, XmlNode _MainNode,string oldHtml)
{
ConvertXmlToHtml(_MainNode, ref Result);
}
public void ConvertXmlToHtml(XmlNode XmlElement, ref string s)
{
PropertyInfo _propList = new PropertyInfo();
#region grid for create arrye
foreach (XmlNode item in XmlElement.ChildNodes)
{
if (item.Name == "AvailableItems" || item.Name == "DataSource" || item.Name == "GridBinding")
{
continue;
}
if ((item as XmlElement).Attributes["Type"].Value == "Grid")
{
string Id_elem = (item as XmlElement).Attributes["ID"].Value;
foreach (XmlNode itemgrigOut in XmlElement.ChildNodes)
{
if (itemgrigOut.Name == "GridBinding")
{
countgrid++;
if (countgrid < 2)
s += "<script> $(document).ready(function() { var object_grid = {" ;
foreach (XmlNode itemgrigIn in itemgrigOut)
{
if (Id_elem == (itemgrigIn as XmlElement).Attributes["ID"].Value)
{
s += Id_elem + " :[ ";
if (Orientation == "Horizontal" || Orientation == "" || Orientation == null)
{
//ساخت گرید مورد نظر
}
else
{
foreach (XmlNode itemcildgrid in itemgrigIn)
{
if ((itemcildgrid as XmlElement).Attributes[Properties.Resources.PropertiesInfo] != null)
_propList = new PropertyInfo() { PropertyList = (itemcildgrid as XmlElement).Attributes[Properties.Resources.PropertiesInfo].Value };
s += " { ID : " + ReturnAttribute((itemcildgrid as XmlElement), "IDgrid", false);
s += ", Visible : " + ReturnAttribute((itemcildgrid as XmlElement), "Visible", false);
s += ", VisibleIndex : " + ReturnAttribute((itemcildgrid as XmlElement), "VisibleIndex", false);
s += ", ReadOnly : " + ReturnAttribute((itemcildgrid as XmlElement), "ReadOnly", false);
s += ", SortOrder : " + ReturnAttribute((itemcildgrid as XmlElement), "SortOrder", false);
s += ", Mask : " + ReturnAttribute((itemcildgrid as XmlElement), "Mask", false);
s += ", IsCondition : " + ReturnAttribute((itemcildgrid as XmlElement), "IsCondition", false);
s += ", ISFormulla : " + ReturnAttribute((itemcildgrid as XmlElement), "ISFormulla", false);
s += ", ReadOnly : " + ReturnAttribute((itemcildgrid as XmlElement), "ReadOnly", false);
s += ", IsForce : " + ReturnAttribute((itemcildgrid as XmlElement), "IsForcegrid", false);
s += "}, ";
}
s += "], ";
}
}
}
}
}
}
}
if (countgrid == CountAll_grid)
s += " } }); </script> ";
#endregion
#region grid
foreach (XmlNode item in XmlElement.ChildNodes)
{
childCount++;
if (item.Name == "AvailableItems" || item.Name == "DataSource" || item.Name == "GridBinding")
{
continue;
}
if ((item as XmlElement).Attributes["Type"].Value == "Grid")
{
string Id_elem = (item as XmlElement).Attributes["ID"].Value;
foreach (XmlNode itemgrigOut in XmlElement.ChildNodes)
{
if (itemgrigOut.Name == "GridBinding")
{
//شمارش تعداد گریدها
countgrid++;
if (countgrid ==0)
{ }
foreach (XmlNode itemgrigIn in itemgrigOut)
{
if (Id_elem == (itemgrigIn as XmlElement).Attributes["ID"].Value)
{
if (Orientation == "Horizontal" || Orientation == "" || Orientation == null)
{
//ساخت گرید مورد نظر
s += string.Format("<br/><div dir = 'rtl' align = 'center' class='table-responsive'><div class='row well'>" +
"<table id=" + Id_elem + "cellpadding='0' cellspacing='0'></table> <div id = pager_" + Id_elem + "></div></div></div>"
);
}
else
{
s += " <div id=" + Id_elem + "myDiv" + " dir='rtl' align='center' class='table-responsive'></div> " +
" <script> $(document).ready(function() {var " + Id_elem + "Divresult = $(" + "'" + "<div id=" + Id_elem + "Div" + " ></div>" + "'" + ") ; " +
" $(" + Id_elem + "Div" + ").append(" + Id_elem + "Divresult); var " + Id_elem + " = new grid(" + "'" + Id_elem + "'" + "," + countgrid + ");" + Id_elem + ".init(); }); </script> ";
$(document).ready(function() {var object_grid = {" + Id_elem +" :[ ";
}
}
}
}
}
}
#endregion
}

Related

MVC Razor, LINQ into J-Query?

What is the best way to pass a LINQ value into J-Query???... How would I go about this?
When the Update link is clicked, it checks the web Grid to see if it is the same on TrailerNumber and CarrierName. If the inputs are the same in both fields as already existing, then allows you to move the data to the current row. (avoid duplication)
Any help would be greatly appreciated!
Checks to see is the inputs already exist in TrailerNumber and CarrierName as the same.
LINQ (Controller):
bool AlreadyInTable = entities.LocationDataMasters.Any(t => t.TrailerNumber == customer.TrailerNumber && t.CarrierName == customer.CarrierName);
//Update event handler.
$("body").on("click", "#webGrid TBODY .Update", function () {
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find(".text").length > 0) {
var span = $(this).find(".label");
var input = $(this).find(".text");
span.html(input.val());
span.show();
input.hide();
}
});
row.find(".Edit").show();
row.find(".Cancel").hide();
row.find(".Clear").show();
$(this).hide();
var customer = {};
customer.LocationID = row.find(".LocationID").find(".label").html();
customer.UserName = row.find(".UserName").find(".label").html();
customer.Location = row.find(".Location").find(".label").html();
customer.Section = row.find(".Section").find(".label").html();
customer.TrailerNumber = row.find(".TrailerNumber").find(".label").html();
customer.CarrierName = row.find(".CarrierName").find(".label").html();
customer.LoadCommodityStatus = row.find(".LoadCommodityStatus").find(".label").html();
customer.DateLoaded = row.find(".DateLoaded").find(".label").html();
customer.PlantLocation = row.find(".PlantLocation").find(".label").html();
$.ajax({
type: "POST",
url: "/Home/UpdateCustomer",
data: '{customer:' + JSON.stringify(customer) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json"
}) //setInterval('location.reload()', 777);
/*************************** Added to Find Duplicates ******************************/
/***********************************************************************************/
/***********************************************************************************/
//(1)Finds the Current Row selected with Edit Link:
var CurrentLocationID = $(this).closest("tr").find('#LocationIDLbl').text();
var CurrentLocation = $(this).closest('tr').find("#LocationLbl").text();
var CurrentSection = $(this).closest('tr').find("#SectionLbl").text();
var CurrentTrailerNumber = $(this).closest('tr').find("#TrailerNumberLbl").text();
var CurrentTrailerNumberVal = $(this).closest('tr').find("#TrailerNumber").val();
var CurrentCarrrierNameLbl = $(this).closest('tr').find("#CarrierNameLbl").text();
var CurrentCarrrierName = $(this).closest('tr').find("#CarrierName").val();
var CurrLocationID = $(this).closest('tr').find("#LocationID").val();
var CurrentIDTrailerCarrier = 'Current Row Location, LocationID: ' + CurrentLocationID + ' Location: ' + CurrentLocation + ' Section: ' + CurrentSection + ' TrailerNumber: ' + CurrentTrailerNumber + ' CarrierName: ' + CurrentCarrrierName;
var TrailerNumberRows = $('#webGrid tr').find("#TrailerNumber").val();
//Identify the current row data to find duplicates against.
/// alert("CurrentIDTrailerCarrier: " + CurrentIDTrailerCarrier);
// $('#webGrid TR').each(function (row, x) {
//=========== This decision is what determines to check for duplicates. ==============
//Loop through Rows that contain the same Trailer Number and Count Rows:
var TrailerNumberContainsCount = $("#webGrid tr > td #TrailerNumberLbl:contains('" + CurrentTrailerNumber + "')").parent().length;
var CarrierNameContainsCount = $("#webGrid tr > td.CarrierName:contains('" + CurrentCarrrierNameLbl + "')").parent().length;
/// alert("TrailerNumberContainsCount: " + TrailerNumberContainsCount + " CarrierNameContainsCount: " + CarrierNameContainsCount);
**if (TrailerNumberContainsCount > 1 && $("#webGrid tr > td #TrailerNumberLbl:contains('" + CurrentTrailerNumber + "')") && $("#webGrid tr > td.CarrierName:contains('" + CurrentCarrrierNameLbl + "')") && CarrierNameContainsCount > 1 ) {**
/****************************************************************/
/************** Find Duplicates Get the LocationID **************/
/****************************************************************/
//Hide rows on TrailerNumber & CarrierName that don't match.
$("#webGrid tr > td #TrailerNumberLbl:not(:contains('" + CurrentTrailerNumber + "'))").filter(':visible').parents().closest('TR').hide();
$("#webGrid tr > td #CarrierNameLbl:not(:contains('" + CurrentCarrrierNameLbl + "'))").filter(':visible').parent().closest('TR').hide(); //Hide Rows that don't contain value.
//Take out the ID that is on the current row to show the duplicate ID only.
var DuplicateID = $('#webGrid tr').filter(':visible').find("#LocationIDLbl:not(:contains('" + CurrentLocationID + "'))").text();
DuplicatesVisibleID = DuplicateID;
//Call the DuplicateID Row to be colored Yellow where the duplicate exists:
$("#webGrid tr #LocationIDLbl:contains('" + DuplicatesVisibleID + "')").closest('tr').filter(':visible').attr('style', 'background-color:#FFFF00;');
$('#webGrid tr:first').parent().show(); //Always show the header.
/********************************************************/
/****************** Start Selection *********************/
/********************************************************/
///$('.SelectedMoveToChecked').attr('disabled', true);
//Allow only one selection of the row to be checked on a checkbox.
$('.SelectedMoveToChecked').click('td', function () {
$(".SelectedMoveIsChecked").not(this).prop('checked', false);
$(".SelectedMoveToChecked").not(this).prop('checked', false);
});
//$(this).closest('tr').find('.RowLocationDupDropDownList').removeAttr('disabled');
$(".SelectedMoveIsChecked").filter(':visible').hide();
$(this).closest("tr").find(".SelectedMoveToChecked").show();
//$('.RowLocationDupDropDownList').hide();
//Gather the data from the row that has the LocationID that is the Duplicate.
var DupRow = $("#webGrid tr #LocationIDLbl:contains('" + DuplicatesVisibleID + "')").closest('tr').filter(':visible');
var DupLocation = DupRow.find('#LocationLbl').text();
var DupSection = DupRow.find('#SectionLbl').text();
var DupTrailerNumber = DupRow.find('#TrailerNumberLbl').text();
var DupCarrierName = DupRow.find('#CarrierNameLbl').text();
var DupLoadCommodityStatus = DupRow.find('#LoadCommodityStatusLbl').text();
var DupDateLoaded = DupRow.find('#DateLoadedLbl').text();
var DupUserName = DupRow.find('#UserNameLbl').text();
var DupPlantLocation = DupRow.find('#PlantLocationLbl').text();
/// alert("DupLocationID: " + DuplicatesVisibleID + " DupLocation: " + DupLocation + " DupSection: " + DupSection + " DupTrailerNumber: " + DupTrailerNumber + " DupCarrierName: " + DupCarrierName);
$(".RowLocationDupDropDownList").hide();
// var $actualRow = $(row);
let text = DupSection + ' ' + DupLocation + ' ' + DuplicatesVisibleID;
$("select option").filter(function () {
//may want to use $.trim in here
return $(this).text() == text;
}).prop('selected', true);
$(".SelectedMoveToChecked").change(function () {
/// e.preventDefault();
//$('select.RowLocationDupDropDownList').each(function () {
if ($("select.SelectedMoveToChecked").closest('checked', true)) {
$(this).closest("tr").find('.RowLocationDupDropDownList').attr('disabled', true).show();
}
if ($('select.SelectedMoveToChecked').closest('checked', false)) {
$('.SelectedMoveToChecked').closest('checked', false).css('visibility', 'hidden');
}
$('select.RowLocationDupDropDownList').children("option:selected").text(DupSection + ' ' + DupLocation + ' ' + DuplicatesVisibleID);
/**********************************************************/
/********** Start Confirmation Dialogue Options ***********/
/**********************************************************/
if ($(this).children("option:selected").val() != '') {
function DuplicateMoveConfirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
var ConfirmStr = "Are you sure, you want to move this? \n" + " TrailerNumber: " + DupTrailerNumber + " CarrierName: " + DupCarrierName + " \n\n " + " From Duplicate Row: \n"
+ " Section: " + DupSection + " Location:" + DupLocation + " Row ID:" + DuplicatesVisibleID + " \n\n ";
if (confirm("Confirm Move Aready Existing To Current Row! " + ConfirmStr + "To Current Row: \n" + " Section: " + CurrentSection + " Location: " + CurrentLocation + " Row ID: " + CurrentLocationID + "?")) {
confirm_value.value = "Yes";
//Trigger/Handler from Drop-Down Box Change.
$("body").on("change", ".SelectedMoveToChecked", function () {
// $("body").on("change", "#TrailerNumber", function (e) {
// e.preventDefault();
/// var row = $(this).closest("tr");
var row = $("#webGrid tr #LocationIDLbl:contains('" + DuplicatesVisibleID + "')").closest('tr').filter(':visible'); //Focus on the other row, not current row.
$("webGrid td", row).each(function () {
if ($(this).find(".text").length > 0) {
span.html(input.val());
}
});
//Tell the row change to be where ID exists by ID Number (RowLocationIDNum) 9 Items where data comes from.
var ToRow = {};
// ToRow.LocationID = RowLocationIDNum;
ToRow.LocationID = CurrentLocationID;
//ToRow.LocationID = DuplicatesVisibleID;
ToRow.UserName = row.find(".UserName").find(".label").html();
ToRow.Location = row.find(".Location").find(".label").html();
ToRow.Section = row.find(".Section").find(".label").html();
ToRow.TrailerNumber = row.find(".TrailerNumber").find(".label").html();
ToRow.CarrierName = row.find(".CarrierName").find(".label").html();
ToRow.LoadCommodityStatus = row.find(".LoadCommodityStatus").find(".label").html();
ToRow.DateLoaded = row.find(".DateLoaded").find(".label").html();
ToRow.PlantLocation = row.find(".PlantLocation").find(".label").html();
// setInterval('location.reload()', 777);
//Set the Clear Event to clear the initial rows.
/// var row = $(this).closest("tr");
var row = $("#webGrid tr #LocationIDLbl:contains('" + DuplicatesVisibleID + "')").closest('tr').filter(':visible'); //Focus on the other row, not current row.
$("td", row).each(function () {
if ($(this).find(".text").length > 0) {
var span = $(this).find(".label");
var input = $(this).find(".text");
$(this).find(".text").show();
$(this).find(".label").hide();
span.html(input.val(null));
span.show();
input.hide();
}
})
row.find(".Cancel").show();
row.find(".Clear").show();
row.find(".Edit").show();
$(this).hide();
var clear = {};
//Clear Duplicate Row After Moving the Data to the Current Row.
// clear.LocationID = DuplicatesVisibleID;
clear.LocationID = row.find(".LocationID").find(".label").html();
clear.UserName = row.find(".UserName").find(".label").html();
clear.Location = row.find(".Location").find(".label").html();
clear.Section = row.find(".Section").find(".label").html();
clear.TrailerNumber = row.find(".TrailerNumber").find(".label").html();
clear.CarrierName = row.find(".CarrierName").find(".label").html();
clear.LoadCommodityStatus = row.find(".LoadCommodityStatus").find(".label").html();
clear.DateLoaded = row.find(".DateLoaded").find(".label").html();
clear.PlantLocation = row.find(".PlantLocation").find(".label").html();
$.ajax({
type: "POST",
url: "/Home/UpdateRowExchange",
data: '{ToRow:' + JSON.stringify(ToRow) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
$.ajax({
type: "POST",
url: "/Home/ClearCustomer",
data: '{clear:' + JSON.stringify(clear) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json"
})
}
})
setInterval('location.reload()', 777);
})
}
else {
confirm_value.value = "Cancel";
setInterval('location.reload()', 777);
}
document.forms[0].appendChild(confirm_value);
}
DuplicateMoveConfirm();
}
});
}
});
//It finds when both TrailerNumber and CarrierName, but also finds when just TrailerNumber, even though CarrierName is not the same.

Convert Json to explicit new object, List initialization c#

Hi I am wondering if there is a way to convert a json object to explicit new object/List object for instance :
Convert this :
{
"name":"John",
"age":30,
"cars":[ "Ford", "BMW", "Fiat" ]
}
into this c# code text:
new className() {
Name = "John",
Age = 30,
Cars = new List (){"Ford", "BMW", "Fiat" }
};
What I want to do is create the equivalent of a json code in to c# code.
You can use the JObject from Newtonsoft library
This is an example from the library
string json = #"{
CPU: 'Intel',
Drives: [
'DVD read/writer',
'500 gigabyte hard drive'
]
}";
JObject o = JObject.Parse(json);
Console.WriteLine(o.ToString());
Output
{
"CPU": "Intel",
"Drives": [
"DVD read/writer",
"500 gigabyte hard drive"
]
}
Or you can use jsonutils to create a C# equivalence class
And then use Newtonsoft to parse the Json object
MyObject obj = JsonConvert.DeserializeObject<MyObject>(jsonContent);
You can use online services like https://www.jsonutils.com/
or
function Convert(jsonStr, classNr) {
var i = classNr == undefined ? 0 : classNr;
var str = "";
var json = JSON.parse(jsonStr);
for (var prop in json) {
if (typeof(json[prop]) === "number") {
if (json[prop] === +json[prop] && json[prop] !== (json[prop] | 0)) {
str += prop + " = " + json[prop] + "M, ";
} else {
str += prop + " = " + json[prop] + ", ";
}
} else if (typeof(json[prop]) === "boolean") {
str += prop + " = " + json[prop] + ", ";
} else if (typeof(json[prop]) === "string") {
str += prop + ' = "' + json[prop] + '", ';
} else if (json[prop] == null || json[prop] == undefined) {
str += prop + ' = null, ';
} else if (typeof(json[prop]) === "object") {
str += prop + " = " + Convert(JSON.stringify(json[prop]), i++) + ", ";
}
}
if (str.endsWith(', ')) {
str = str.substring(0, str.length - 2);
}
return "new Class" + i + "{ " + str + " }";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="tin" cols="100" rows="6">
{"A":12}
</textarea>
<input type="button" value="Just do it!" onclick="$('#result').text(Convert($('#tin').val()));" />
<div id="result"></div>
from https://stackoverflow.com/a/34590681/1932159

Html not displaying in View that was created in Controller

When I created a method in a controller I would like the output which is HTML to be displayed in the view. Although I see the functions results as the expected html it does not display in the page.
I've tried the HtmlHelper Html.Raw
<table class="table table-bordered table-framed" id="seconDTable" style="display:block;height:100%;">
<tbody>
#if (caseFile.Length > 0 && RenamedCaseFileName.Length > 0)
{
<tr>
<td style="width: 100%;">
<input type="checkbox" id="CheckBox" title="Select All Bookmarks" onchange="changeCheckBox();" class="styled" />
<span>Select All</span>
</td>
</tr>
if (oGdPicturePDFstatus == GdPicture14.GdPictureStatus.OK)
{
int rootID = oGdPicturePDF.GetBookMarkRootID();
oGdPicturePDFstatus = oGdPicturePDF.GetStat();
if (oGdPicturePDFstatus == GdPicture14.GdPictureStatus.OK)
{
IHtmlString str = new HtmlString(GetPDFBookmarks.ParseBookmarksOutlines(oGdPicturePDF, rootID, 0));
Html.Raw(str);
}
else
{
if (oGdPicturePDFstatus == GdPicture14.GdPictureStatus.PropertyNotFound)
{
<tr>
<td style="width: 100%;">
This PDF document doesn't contain any bookmarks.
</td>
</tr>
}
}
}
oGdPicturePDF.Dispose();
}
</tbody>
</table>
Function:
public string ParseBookmarksOutlines(GdPicturePDF oGdPicturePDF, int bookmarkID, int level)
{
string title = "";
GdPictureStatus status = GdPictureStatus.OK;
string cssType = string.Empty;
string TableRows = string.Empty;
while (true)
{
title = oGdPicturePDF.GetBookMarkTitle(bookmarkID);
status = oGdPicturePDF.GetStat();
if (level == 0)
{
cssType = "ParentsourcefileCheckBox";
}
else
{
cssType = "ChildsourcefileCheckBox";
}
if (status == GdPictureStatus.OK)
{
TableRows = TableRows + "<tr><td style=\"width: 100 %; \">";
TableRows = TableRows + "<input name=\"sourcefileCheckBox\" type=\"checkbox\" class=\"" + cssType + "\" id=\"checkBox\" value=\"" + bookmarkID + "\" />";
TableRows = TableRows + "<span>" + title + "</span>";
TableRows = TableRows + "</td></tr>";
}
else
{
TableRows = TableRows + "<tr><td>";
TableRows = TableRows + "Title: this error occurs - " + status.ToString() + " Level: " + level.ToString() + "\n";
TableRows = TableRows + "</td></tr>";
//message = message + "Title: this error occurs - " + status.ToString() + " Level: " + level.ToString() + "\n";
}
if (bookmarkID == 0)
{
break;
}
}
return TableRows;
}
I'm expecting the checkboxes to be displayed on the final rendered page instead it does not display ay all.
enter image description here
The answer was the following:
#Html.Raw(HttpUtility.HtmlDecode(GetPDFBookmarks.ParseBookmarksOutlines(oGdPicturePDF, rootID, 0)));
It was located in the post:
Return html string from controller and display in view

Call javascript function from asmx

I want to return javascript function from asmx as string like following..
All html tags return but checkNewMsg variant 'script tag' doesnt return!
What happens really ?
Please advice
<script type="text/javascript">
function getWindow(FromUserID, UserID, PerID, UserName) {
$.ajax({
type: "POST",
url: "TestMessageService.asmx/OpenWindow",
data: "{'FromUserID': '" + FromUserID + "', 'ClickedUserID': '" + UserID + "', 'ClickedPerID': '" + PerID + "', 'ClickedUserName': '" + UserName + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var msgs = response.d;
$('#div_Panel').append(msgs).fadeIn("slow");
var elements = $('.panelContent');
for (var i = 0; i < elements.length; i++) {
elements[i].scrollTop = elements[i].scrollHeight;
}
},
failure: function (msg) {
$('#div_Panel').text(msg);
}
});
}
</script>
[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public string OpenWindow(string FromUserID, string ClickedUserID, string ClickedPerID, string ClickedUserName)
{
string checkNewMsg = "<script type=\"text/javascript\">window.setInterval(fc_" + ClickedUserName.Replace(" ", "") + ", 10000); function fc_" + ClickedUserName.Replace(" ", "") + "() { alert('" + ClickedUserName + "'); }</script>";
StringBuilder sb = new StringBuilder();
sb.Append(checkNewMsg + "<div class=\"ch_Box\">");
sb.Append("<div class=\"ch_Header\">");
sb.Append("<div style=\"float:left;margin-top: 9px;margin-left: 8px;\"><img src=\"Images/Status.png\"></div>");
sb.Append("<div id=\"roomUsers\" class=\"ch_HeaderItem\">" + ClickedUserName + "</div>");
sb.Append("<div onclick=\"closePanel(this)\" style=\"width: 23px; height: 27px; cursor: pointer; position: absolute; margin-left: 232px;\"><img style=\"height: 20px; margin-top: 4px;\" src=\"Images/close.png\"></div>");
sb.Append("<div id=\"cont_" + ClickedUserID + "\" class=\"panelContent\">" + FillMessages(roomID, FromUserID.ToInt()) + "</div>");
sb.Append("<div class=\"ch_Text\">");
sb.Append("<input id=\"msg_" + FromUserID + "_" + ClickedUserID + "_" + ClickedPerID + "_" + roomID + "\" type=\"text\" class=\"inp\" onkeypress=\"PushText(this)\" autocomplete=\"off\" /></div>");
sb.Append("</div></div>");
return sb.ToString();
}
I don't know why doesn't return script tag an asmx but when i remove the tag and then in the js side while i add script' tag before return value the problem is solved.
Just like this;
In asmx side;
string checkNewMsg = "window.setInterval(fc_" + ClickedUserName.Replace(" ", "") + ", 10000); function fc_" + ClickedUserName.Replace(" ", "") + "() { alert('" + ClickedUserName + "'); }#func#";
In Js Side;
success: function (response) {
var msgs = response.d;
var arrCont = msgs.split('#func#');
var MsgCont = "<script type=\"text/javascript\">" + arrCont[0] + "<\/script>";

Why is the href of anchor tag written in code behind not accepting 'aspx'

I have a calender control and on selecting a respective date, I need to display Today's Due and Over due as two section in an accordion. I have written the div for accordion in code behind and set style.css to give the look of Accordion. The data from code behind is converted into json and displayed. The code behind is as follows:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string CalenderBinderAccordian()
{
try
{
//Code to fetch productGroup is not shown
foreach (var p in productGroup)
{
var todoCount = 1;
string todoString = "";
int uniqueID = Guid.NewGuid().GetHashCode();
todoString = "<div class='accordion vertical'><section id='" + uniqueID + "' style='overflow-y: scroll;'> <h2><b>Due Today</b></h2>";
foreach (var t in p.todo)
{
var tempAmt = String.Empty;
if ((t.Amount == null) || t.Amount == String.Empty)
tempAmt = "0";
else
tempAmt = Convert.ToDecimal(t.Amount.ToString()).ToString();
todoString += "<p><div style='padding:5px 0px; border-bottom:dashed 1px #dddddd;'><b>" + todoCount.ToString() + "</b>. " + t.ProductName + "<span style='text-align:right; padding-right:5px;'> $" + tempAmt + "</span><a href='www.google.com' target='_blank' style='text-decoration:none;'><b>Pay Now</b></a></div></p>";
todoCount++;
}
todoString += "</section>";
var overDue = temps.Select(x => new { x.DueDate }).Distinct().ToList();
int overDueCount = 0;
uniqueID = Guid.NewGuid().GetHashCode();
todoString += "<section id='" + uniqueID + "'> <h2><b>Over Due</b></h2>";
int todoCount1 = 1;
for (int i = 0; i < overDue.Count(); i++)
{
if ((Convert.ToDateTime(overDue[i].DueDate) - Convert.ToDateTime(p.dates)).Days < 0)
{
overDueCount++;
var overDueList = temps.FindAll(x => x.DueDate.Equals(overDue[i].DueDate)).ToList();
foreach (var t in overDueList)
{
var tempAmt = String.Empty;
if ((t.Amount == null) || t.Amount == String.Empty)
tempAmt = "0";
else
tempAmt = Convert.ToDecimal(t.Amount.ToString()).ToString();
//Error occurs when the href is given as aspx
todoString += "<p><div style='padding:5px 0px; border-bottom:dashed 1px #dddddd;'><b>" + todoCount1.ToString() + "</b>. " + t.ProductName + "<span style='text-align:right; padding-right:5px;'> $" + tempAmt + "</span><a href='PaymentDetails.aspx' target='_blank' style='text-decoration:none;'><b>Pay Now</b></a></div></p>";
todoCount++;
todoCount1++;
}
}
}
todoString = todoString + "</section></div>\",\"count\":\"" + todoCount + "\"},";
jsonString = jsonString + String.Format("{{\"{0}\" : \"{1}\",\"{2}\" : \"{3}", "dates", p.dates, "todo", todoString);
if (overDueCount.Equals(0))
{
jsonString = jsonString.Replace("</section><section id='" + uniqueID + "'> <h2><b>Over Due</b></h2></section>", "</section>");
}
}
jsonString = jsonString.TrimEnd(',');
jsonString = '[' + jsonString + ']';
string data= jsonString; JavaScriptSerializer().Serialize(productGroup);
return data;
}
catch (Exception ex)
{
throw;
}
}
//How to data is converted to Jsonvar tododate = [];
$(window).bind('loaded', function () {
$.ajax({
type: "POST",
url: "ChartBinder.asmx/CalenderBinderAccordian",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
tododate = JSON.parse(msg.d);
},
error: function (msg) {
alert("error");
}
});
});
Kindly note when the href is given as www.google.com the functionality works well but when it is given as PaymentGateway.aspx It does not display date in accordion format rather shows error alert.
Using Firebug, Noticed the following Error:
Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property
Solution: Tried changing the configuration :
<configuration>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>

Categories

Resources