I want to create a custom grid which will have three columns and rows can be of any number that depends on the data. But my problem is the data is available as json. I have created grid like structure many times but that is with model and collections like:
First creating the divs for columns
#{
if (Model.MessageList.Count > 0)
{
<div class="GridView_Div">
<div class="GridHeader_Div">
<div class="GridHeaderColoums_Div">Message</div>
<div class="GridHeaderColoums_Div">Sent Date</div>
<div class="GridHeaderColoums_Div">Receive Date</div>
<div class="GridHeaderColoums_Div">Actions</div>
</div>
<div class="GridData_Div">
#{
for (int i = 0; i < Model.MessageList.Count; i++)
{
string resultMessage = string.Empty;
string newMessage = string.Empty;
string result1 = Model.MessageList.ElementAt(i).Message;
int length = result1.Length;
if (length > 5)
{
resultMessage = result1.Substring(0, 5);
newMessage = resultMessage + "......";
}
else
{
resultMessage = result1.Substring(0);
newMessage = resultMessage + "......";
}
<div class="Grid_Row">
<div class="GridData_Coloums">
#newMessage
</div>
<div class="GridData_Coloums">#Model.MessageList.ElementAt(i).Sent_Date</div>
<div class="GridData_Coloums"> #Model.MessageList.ElementAt(i).Receive_Date</div>
<div class="GridData_Coloums">
<input type="button" value="Delete" id="#Model.MessageList.ElementAt(i).pkMessageId"/>
</div>
</div>
}
}
</div>
</div>
}
else
{
<div style="width: 50%; float: left; margin-left: 10%;">No Message Found</div>
}
}
But how can I create a grid like structure in Json data?
Please help me with this case. Thank you very much
This has been a challenge for me and I accomplished it.
In the view
$(document).ready(function () {
$("#hdnPkClientId").val('');
$("#txt_Autocomplete").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Home/SearchClientDetail",
data: "{'searchtext':'" + document.getElementById('txt_Autocomplete').value + "'}",
dataType: "json",
success: function (data) {
response($.map(data.Data, function (item) {
return {
label: item.Name,
value: item.id,
data: item
};
}));
},
error: function (xhr)
{ }
});
},
select: function (event, ui) {
var detailArr = ui.item.label.split(',');
$("#txt_Autocomplete").val(detailArr[0]);
$("#hdnPkClientId").val(ui.item.data.Id);
$("#Evaluation_Anch").attr("href", "/Evaluation/Index?Client_ID=" + ui.item.data.Id);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/ClientHome/GetSelectedClientDetails",
data: "{'ClientId':'" + document.getElementById('hdnPkClientId').value + "'}",
dataType: "json",
success: function (data) {
$("#Client_Name").html(data.Info.Name);
$("#Client_Address").html(data.Info.Address);
$("#Client_OtherAddressDetails").html(data.Info.OtherAddressDetails);
$("#Client_DOB").html(data.Info.DOB);
$("#Client_Phone").html(data.Info.Phone);
$("Client_MobilePhone").html(data.Info.Mobile_Phone);
var DataDiv = "<table width='100' border='0' cellspacing='0' cellpadding='0'> <tr> <th class='head'>Date</th> <th class='head'>Document Type</th> <th class='head'>Provider</th> </tr>";
for (var iRow = 0; iRow < data.Info.Prev_Doc_List.length; iRow++) {
var temp = data.Info.Prev_Doc_List[iRow];
DataDiv += "<tr>";
DataDiv += "<td>" + temp.Created_Date + "</td>";
DataDiv += "<td><a id='" + temp.Page_ID + "' href='" + temp.RedirectAddress + "'>" + temp.Doc_type + "</a></td>";
DataDiv += "<td>" + temp.Provider + "</td>";
DataDiv += "</tr>";
}
DataDiv += "</table>";
$("#PreviousDocumentDiv").html(DataDiv);
},
error: function (xhr)
{ }
});
return false;
}
});
});
In controller
[HttpPost]
public ActionResult GetSelectedClientDetails(string ClientId)
{
ProgressNotesService objService = new ProgressNotesService();
var Client_Detail = objService.GetSelectedClient(Convert.ToInt32(ClientId));
if (Client_Detail != null)
{
Session["Client_ID"] = Client_Detail.Id;
}
return Json(new { Info = Client_Detail });
}
In Service
public ClientDetailModel GetSelectedClient(int ClientID)
{
ClientDetailModel ClientDetail = new ClientDetailModel();
List<PreviousDocuments> objDocsList = new List<PreviousDocuments>();
using (DataContext DB = new DataContext())
{
var Row = DB.tbl.Where(m => m.ID == ClientID).FirstOrDefault();
if (Row != null)
{
ClientDetail.Id = Row.ID.ToString();
ClientDetail.Name = Row.First_Name + " " + Row.Last_Name;
ClientDetail.Address = Row.Address;
ClientDetail.Client_DOB = (DateTime)Row.DOB;
ClientDetail.DOB = ClientDetail.Client_DOB.ToString("MM/dd/yyyy");
ClientDetail.OtherAddressDetails = (Row.City == "" || Row.City == null ? "N/A" + " " + "," : Row.City + " ,") + (Row.State == "" || Row.State == null ? "N/A" + " " + "," : Row.State + " ,") + (Row.ZipCode == "" || Row.ZipCode == null ? "N/A" : Row.ZipCode);
ClientDetail.Phone = Row.Phone;
ClientDetail.Mobile_Phone = Row.OtherContact_Phone;
var ProgressNoteRecords = DB.ProgressNotes.Where(m => m.FkReferralID == ClientID).ToList();
if (ProgressNoteRecords.Count() > 0)
{
for (int iRow = 0; iRow < ProgressNoteRecords.Count(); iRow++)
{
objDocsList.Add(new PreviousDocuments
{
Created_Date = Convert.ToString(ProgressNoteRecords.ElementAt(iRow).Created_Date),
Doc_type = "Progress Note",
Provider = " blah blah",
Page_ID = Convert.ToString(ProgressNoteRecords.ElementAt(iRow).Id),
RedirectAddress = "../ProgressNote/Add?ProgressNote_ID=" + Convert.ToString(ProgressNoteRecords.ElementAt(iRow).Id)
});
}
}
var Ref = DB.tblrefServices.Where(m => m.ID == ClientID).ToList();
if (Ref.Count > 0)
{
for (int iRow = 0; iRow < Ref.Count(); iRow++)
{
objDocsList.Add(new PreviousDocuments
{
Created_Date = Convert.ToString(Ref.ElementAt(iRow).First_Name),
Doc_type = "Referral Service",
Provider = "blah blah",
Page_ID = Convert.ToString(Ref.ElementAt(iRow).ID)
});
}
}
ClientDetail.Prev_Doc_List = objDocsList;
}
}
return ClientDetail;
}
In model
public class ClientDetailModel
{
public ClientDetailModel()
{
Prev_Doc_List = new List<PreviousDocuments>();
}
public string Name { get; set; }
public string Id { get; set; }
public string DOB { get; set; }
public string Address { get; set; }
public string OtherAddressDetails { get; set; }
public string Phone { get; set; }
public string Mobile_Phone { get; set; }
public DateTime Client_DOB { get; set; }
public List<PreviousDocuments> Prev_Doc_List { get; set; }
}
public class PreviousDocuments
{
public string Created_Date { get; set; }
public string Doc_type { get; set; }
public string Provider { get; set; }
public string Page_ID { get; set; }
public string RedirectAddress { get; set; }
}
You can use KnockoutJS to bind your json data to your custom grid
what about using any template engines like jsrender. where you can convert provided mvc's view code to templates. Then pass the json to the template that will render grid in desired element.
refer the below link for more details
http://borismoore.github.io/jsrender/demos/demos.html
http://www.jsviews.com/#jsrender
Related
What's the Blazor equivalent of this Knockout.js data-binding?
I can easily create a foreach loop through a C# List<T> object and bind to the object's properties however I'm struggling with this as the binding is for the id attributes.
HTML code:
<div data-bind="foreach : combinedArr">
<div data-bind="with: $data.recordCo">
<table id="tableFull">
<tbody>
<tr>
<td class="fixed-width iconCol" data-bind="with: $parent.targetCo">
<button data-bind="attr: { 'data-target': $data[0].tableTargetID, id: $data[0].buttonID }" data-toggle="collapse" type="button" onclick="glyphChanger(this.id)" class="btn btn-default iconButton glyphicon glyphicon-chevron-right" aria-label="Left Align" aria-hidden="true"></button>
</td>
</tr>
</tbody>
</table>
</div>
<div class="tbAdj panel panel-collapse collapse" data-bind="attr: { id: $data.countCo }">
<table class="table table-condensed tableSize tableSpacer" id="tableFull">
<tbody data-bind="foreach: $data.jsonCo">
....
</tbody>
</table>
</div>
</div>
Javascript code:
self.combinedArr = ko.observableArray();
self.post = function () {
voidNotification = false;
self.combinedArr.removeAll();
$.post(this.api + "/tabular", {
value: this.logSource()
}).success(
function (d) {
var counter = 0;
$.each(d, function (i, o) {
var objArr = JSON.parse(o);
//Parse a second time to access the objects individually
var recordParsed = JSON.parse(objArr[0]);
var jsonParsed = JSON.parse(objArr[1]);
//Data to populate the expandable table
jsArr = [];
for (var x in jsonParsed) {
jsArr.push({ jfieldName: jsonParsed[x].Name, jfieldValue: jsonParsed[x].Value });
}
//ID for the button that expands and collapses the table
var buttonID = "btUniqID" + counter;
//The id of the table - needs to be in the same array as the buttonID
var tableTargetID = "#jsonTable" + counter;
var idArr = [];
idArr.push({ tableTargetID: tableTargetID, buttonID: buttonID });
//The id for that table that needs to be on its own
var uniqueTableID = "jsonTable" + counter;
//Combine all the data and push to the combinedArr
self.combinedArr.push({ recordCo: recordParsed, jsonCo: jsArr, countCo: uniqueTableID, targetCo: idArr });
//Incremented for unique button ids
counter++;
});
if (counter === 0) {
self.FaultFound(true);
self.FaultText("Data could not be parsed");
$("#recordTable").css("display", "none");
} else {
self.FaultFound(false);
//Check if transaction is void
VoidHandler();
//Hides the loading animation
self.ShowDetailsLoading(false);
//Show the recordsTable
$("#recordTable").css("display", "block");
}
})
.error(
function (d) {
alert('failed ' + d);
}
);
}
I've created a C# class equivalent to self.combinedArr with the rows variable below:
public List<CombinedRow> rows = new List<CombinedRow>();
private async Task OnParseClicked()
{
try
{
var response = await Http.PostAsJsonAsync("api/TLogParser/Records", new TLogMessageRequestDto(logMessage: inputMessage));
parsedMessage = await response.Content.ReadFromJsonAsync<IEnumerable<RecordItem>>();
var jsArray = new List<Record>();
foreach (var m in parsedMessage)
{
jsArray.Add(new Record { jfieldName = m.MessageId, jfieldValue = m.RecordBody });
}
var counter = 0;
foreach (var m in parsedMessage)
{
//ID for the button that expands and collapses the table
var buttonID = "btUniqID" + counter;
//The id of the table - needs to be in the same array as the buttonID
var tableTargetID = "#jsonTable" + counter;
var row = new Row() { ButtonId = buttonID, TableTargetId = tableTargetID };
//The id for that table that needs to be on its own
var uniqueTableID = "jsonTable" + counter;
var combinedRow = new CombinedRow { recordCo = m, JsonCo = jsArray, CountCo = uniqueTableID, TargetCo = row};
rows.Add(combinedRow);
counter++;
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
public class CombinedRow
{
public RecordItem recordCo { get; set; }
public Row TargetCo { get; set; }
public string CountCo { get; set; }
public List<Record> JsonCo { get; set; }
}
public class Row
{
public string ButtonId { get; set; }
public string TableTargetId { get; set; }
}
public class Record
{
public string jfieldName { get; set; }
public string jfieldValue { get; set; }
}
However, I'm not sure on the HTML/Blazor binding part of how to bind to the id attributes.
I only get the text message Selektoni Tipin, but I dont get any values from the tables I only get undefined
AJAX script
script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/Dokument/Dokument",
data: "{}",
success: function (data) {
var s = '<option value="-1">Selektoni Tipin</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].Id_Tipi + '">' + data[i].Emri_llojit + '</option>';
}
$("#tipiDropdown").html(s);
}
});
});
</script>
Controller method
public ActionResult Dokument()
{
return View();
}
// GET: NgarkoDokument
public ActionResult GetTipi(int tipiId)
{
Test_kristiEntities db = new Test_kristiEntities();
return Json(db.Tipi.Select(x => new
{
Id_Tipi = x.Id_Tipi,
Emri_llojit = x.Emri_llojit
}).ToList(), JsonRequestBehavior.AllowGet);
// return View();
}
Model i built with some tables
public class NgarkoDokument
{
public Dokumenti Dokumenti { get; set; }
public Fusha_Indeksimit FushaIndeksimit { get; set; }
public Vendndodhja_Fizike Vendndodhja_fizike { get; set; }
public Tipi Tipi { get; set; }
}
And here is the html
<select title="Lloji i dokumentit" name="lloji" class="form-control col-md-3 box" id="tipiDropdown"> </select>
Refer to the comment inside the ajax success function:
function CreateProjectTree(sc)
{
$.ajax({
type: "POST",
url: "../api/projects/SearchProjects",
data: sc,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data)
{
if ($(data).length === 1)
{
window.location.replace("../ViewProjectDetails.aspx?ProjectId=" + //here's where I need to get the id;
}
else
{
buildTree(data);
}
},
});
}
This is what the controller looks like for the post:
public class ProjectsController : ApiController
{
public List<Item> SearchProjects(GBLProjectSearchCriteria searchCriteria)
{
var ProjectSearchResult = new ProjectSearchResultController();
searchCriteria.SearchType = "P";
searchCriteria.QueryString = "?ProjectId=";
var GBLProjectSearchResultListData = ProjectSearchResult.GetProjectSearchResultList(searchCriteria);
var projectList = (from GBLProjectSearchResult item in GBLProjectSearchResultListData
select new Item
{
Id = item.Id,
Title = item.Title,
Url = item.NavigateUrl + item.QueryString
}).ToList();
foreach (var project in projectList)
{
//seasons
project.Items = new List<Item>();
var SeasonSearchResult = new ProjectSearchResultController();
searchCriteria.Id = project.Id;
searchCriteria.SearchType = "S";
searchCriteria.QueryString = "?ProjectId=" + project.Id + "&SeasonId=";
var GBLSeasonSearchResultListData = SeasonSearchResult.GetProjectSearchResultList(searchCriteria);
foreach (var season in from GBLProjectSearchResult item in GBLSeasonSearchResultListData
select new Item
{
Id = item.Id,
Title = item.Title,
Url = item.NavigateUrl + item.QueryString
})
{
project.Items.Add(season);
project.HasChildren = (project.Items.Count > 0);
}
foreach (var season in project.Items)
{
//episodes
season.Items = new List<Item>();
var episodeSearchResult = new ProjectSearchResultController();
searchCriteria.Id = season.Id;
searchCriteria.SearchType = "E";
searchCriteria.QueryString = "?ProjectId=" + project.Id + "&SeasonId=" + season.Id + "&EpisodeId=";
var GBLEpisodeSearchResultListData = episodeSearchResult.GetProjectSearchResultList(searchCriteria);
foreach (GBLProjectSearchResult item in GBLEpisodeSearchResultListData)
{
var episode = new Item
{
Id = item.Id,
Title = item.Title,
Url = item.NavigateUrl + item.QueryString
};
season.Items.Add(episode);
season.HasChildren = (season.Items.Count > 0);
}
}
}
return projectList;
}
public class Item
{
readonly string take2Root = ConfigurationManager.AppSettings["Take2Root"];
private string url;
public int Id
{
get;
set;
}
public string Title
{
get;
set;
}
public bool HasChildren
{
get;
set;
}
public List<Item> Items
{
get;
set;
}
public string Url
{
get
{
return url;
}
set
{
url = take2Root + value.Replace("..", "");
}
}
}
}
I need to get the ID of the parent node returned by this controller.
I would know how to work with a GET request, however, I have to do a POST here and I'm unsure on how to extract the ID inside the ajax success function.
Can someone give me a hand?
Thanks!
inside your if ($(data).length === 1) statement you can add debugger; (or set a break-point) then examine the data object using chrome's developer tools. The id you're after will be something like data.objects[0].id
I have been having a issue when I post form data to my webservice. When I debug the web service the parameter messagepost has a count of 1 but the object data is empty, but when I look at the object in the request I can see that the object is populated. I've been searching and racking my brain for an hour and can't see me to get it to work. So maybe someone here can help me out.
Javascript
function getEmptyLeg() {
var chkTail = $("#elTail").is(':checked');
var chkType = $("#elType").is(':checked');
var chkNBAA = $("#chkNBAA").is(':checked');
var chkCategory = $("#elCategory").is(':checked');
var itineraryList = new Array();
var itinerary = new Object();
itinerary.Time = "";
itinerary.Arrival = $("#elTo").val();
itinerary.Departure = $("#elFrom").val();
itinerary.ArrivalDate = getDate("#elEndDate");
itinerary.DepartureDate = getDate("#elStartDate");
itineraryList.push(itinerary);
var messagepost = new Object();
messagepost.Types = "";
messagepost.Categories = "";
messagepost.ShowTail = chkTail;
messagepost.ShowType = chkType;
messagepost.SendToNBAA = chkNBAA;
messagepost.DirectoryAircraft = false;
messagepost.ShowCategory = chkCategory;
messagepost.Price = $("#elPrice").val();
messagepost.NBAAEmail = $("#txtEmail").val();
messagepost.MessageItinerary = itineraryList;
messagepost.AircraftID = $("select#elAircraft").val();
return messagepost;
}
function saveMessage() {
var options = "";
var type = $("#hdfType").val();
var userid = $('#<%= hdfUserID.ClientID %>').val();
var message = $("#<%= txtMessage.ClientID %>").val();
var timezone = $('#<%= hdfTimezone.ClientID %>').val();
$('#<%= sltUsers.ClientID %> option:selected').each(function (i) {
options += $(this).val() + ",";
});
var messagepost = new Array();
messagepost.push(getEmptyLeg());
$.ajax({
type: "Post",
async: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "/Resources/MessageWebService.asmx/SaveMessage",
data: "{ 'message':'" + message + "',"
+ "'options':'" + options + "',"
+ "'url':'" + $(location).attr('href') + "',"
+ "'userid':'" + userid + "',"
+ "'messageid':'" + 0 + "',"
+ "messagepost:" + JSON.stringify(messagepost) + ","
+ "'postType':'" + type + "' }",
success: function (data) {
$('#messages').prepend($(data.d).fadeIn('slow'));
growlMessage('Message was successfully');
},
error: function (data) {
showError(data.responseText);
}
});
}
web service
[WebMethod]
public string SaveMessage(string message, string options, string url, string userid, string messageid, List<MessagePost> messagepost, string postType) {
}
Request from chrome
{ 'message':'empty leg','options':'Public,','url':'http://localhost/portal/quote.aspx?qid=254','userid':'d2703dd0-c743-4995-ac93-5cfab7fa5205','messageid':'0',messagepost:[{"Types":"","Categories":"","ShowTail":true,"ShowType":true,"SendToNBAA":true,"DirectoryAircraft":false,"ShowCategory":true,"Price":"2500","NBAAEmail":"chad.neiro#avianis.com","MessageItinerary":[{"Time":"","Arrival":"KSAN","Departure":"ENNA","ArrivalDate":"12/21/2012","DepartureDate":"12/21/2012"}]}],'postType':'4' }
message post class
public class MessagePost
{
Boolean ShowTail { get; set; }
Boolean ShowType { get; set; }
Boolean SendToNBAA { get; set; }
Boolean ShowCategory { get; set; }
Boolean DirectoryAircraft { get; set; }
string Types { get; set; }
string Price { get; set; }
string NBAAEmail { get; set; }
string AircraftID { get; set; }
string Categories { get; set; }
List<MessageItinerary> ItineraryList { get; set; }
}
public class MessageItinerary
{
string Time { get; set; }
string Arrival { get; set; }
string Departure { get; set; }
string ArrivalDate { get; set; }
string DepartureDate { get; set; }
string Preference { get; set; }
}
Like saarps suggests in the comments, I also believe this has to do with JSON and deserialization of the data.
I gave up paramaters in my WebMethods early, and retrieve the data from the Request instead.
Example, the following code:
[WebMethod]
public string SaveMessage(string message) {
//Do something
}
would instead be written like this:
[WebMethod]
public string SaveMessage() {
string message = HttpContext.Current.Request.Form["message"];
//Do something
}
I have a ViewModel and a DropDownList with some values on my page:
public class MyViewModel
{
public string SelectedItemDrop1 { get; set; }
public string SelectedItemDrop2 { get; set; }
public string SelectedItemDrop3 { get; set; }
public List<OptionViewModel> Options { get; set; }
}
public class OptionViewModel
{
public string Number { get; set; }
public string Option { get; set; }
}
And, into my View:
#using (Html.BeginForm("Save", "Controller", FormMethod.Post))
{
<ul id="cursos">
<li>
#Html.DropDownListFor(c => c.SelectedItemDrop1,
new SelectList(Model.Options, "Number", "Option", Model.SelectedItemDrop1))
Choose 1
</li>
<li>
#Html.DropDownListFor(c => c.SelectedItemDrop2,
new SelectList(Model.Options, "Number", "Option", Model.SelectedItemDrop2))
Choose 2
</li>
<li>
#Html.DropDownListFor(c => c.SelectedItemDrop3,
new SelectList(Model.Options, "Number", "Option", Model.SelectedItemDrop3))
Choose 3
</li>
</ul>
}
When I use Javascript to change options from these select elements, my return is null. What's the problem? Thank you so much!!!
EDIT:
My javascript code:
$("#cursos li select").each(function (i, item) {
$(this).change(function () {
updateCursos($(this), 7);
});
$(this).blur(function () {
if ($(this).val() != -1) {
$(this).attr('disabled', 'disabled');
}
});
});
function updateCursos(select, avaiableCourses) {
var selecteds = '';
$("#cursos li select").each(function (i, item) {
var selected = $(item).val();
if (selected != -1)
selecteds += selected + ',';
});
var arr = selecteds.split(',');
$("#cursos li select").each(function (i, item) {
if ($(item).val() != select.val()) {
var oldValue = $(item).val();
if ($(item).val() == -1) {
var options = "<option value='-1'></option>";
for (i = 1; i <= avaiableCourses; ++i) {
if (select.val() != i && !contains(i, selecteds)) {
options += "<option value='" + i + "'>" + i + "ª option</option>";
}
}
options += "<option value='0'>Don't want it</option>";
$(item).children("option").remove();
$(item).html(options);
$(item).val(oldValue);
}
}
});
}
This way I'm sure that works, not even being javascript.
If the values are not being filled are coming from the database, with fixed values example: active, inactive, do the following
Create an enumerated type with these values
After the controller transforms this type enumerated in list using an internal class, turn it into a enumerable and go to the dropdownlist
example of usage:
# Html.DropDownListFor (model => model.chamados.UrgenciaId, new SelectList (ViewBag.urgencia, "Id", "Name"))