how to display the search result from the grid using jquery? - c#

i have my jquery like,
$(document).ready(function () {
$('#NotAllotedStudentsGrid').jtable({
title: 'Allot to Students below',
paging: true,
pageSize: 5,
sorting: true,
defaultSorting: 'Name ASC',
selecting: true, //Enable selecting
multiselect: true, //Allow multiple selecting
selectingCheckboxes: true, //Show checkbo.xes on first column
actions: {
listAction: '#Url.Action("NotAllotedStudentsList")',
//deleteAction: '#Url.Action("DeleteStudent")',
//updateAction: '#Url.Action("UpdateStudent")',
//createAction: '#Url.Action("CreateStudent")'
},
fields: {
UserNo: {
key: true,
create: false,
edit: false,
list: false
},
Name: {
title: 'Name',
width: '15%'
},
Batch: {
title: 'Batch',
},
EmailAddress: {
title: 'Email address',
},
ContactNo: {
title: 'Contact No',
type: 'textarea',
}
}
});
//Load student list from server
$('#NotAllotedStudentsGrid').jtable('load');
$('#SearchFor').button().click(function () {
var SearchForValue = $("#NotAllotedStudentsList").val();
var StudentInputTypeValue = $("#InputType").val();
var options = {};
options.type = "POST";
options.url = "/Dashboard/NotAllotedStudentsList/";
options.data = JSON.stringify({ model: { SearchFor: SearchForValue, StudentInputType: StudentInputTypeValue } });
options.dataType = "json";
options.contentType = "application/json";
$.ajax(options);![enter image description here][1]
});
i have my controller like,
public ActionResult NotAllotedStudentsList(AllotQuestionSet model,int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)
{
List<TutorStudentsGridModel> tutorStudentsGridModelList = new List<TutorStudentsGridModel>();
User userDetails = _sessionHelper.Get<User>(KrackemSessionConstants.UserDetails);
StudentResponse studentListResponse = new StudentResponse();
int questionSetNo = Int32.Parse(_sessionHelper.Get<string>(KrackemSessionConstants.QuestionSetNo));
if (model.SearchFor == null)
{
StudentRequest studentRequest = new StudentRequest
{
TutorUserNo = userDetails.UserNo,
QuestionSetNo = questionSetNo
};
studentListResponse = _questionSetServiceHelper.GetNotAllottedStudentsByTutorNo(studentRequest);
}
//Get Not Allotted Students By Name
if (model.SearchFor != null && model.StudentInputType == StudentInputType.Name)
{
StudentRequest studentRequest = new StudentRequest
{
TutorUserNo = userDetails.UserNo,
QuestionSetNo = questionSetNo,
InputString = model.SearchFor
};
studentListResponse = _questionSetServiceHelper.GetNotAllottedStudentsByName(studentRequest);
}
foreach (StudentContract studentDetails in studentListResponse.StudentList)
{
TutorStudentsGridModel tutorStudentsGridModel = MappingEngineFactory.GetMappingEngine().Map<StudentContract, TutorStudentsGridModel>(
studentDetails);
tutorStudentsGridModel.Id = studentDetails.UserNo;
tutorStudentsGridModelList.Add(tutorStudentsGridModel);
}
if (jtSorting != null)
tutorStudentsGridModelList = ControllerHelper.SortList(jtSorting, tutorStudentsGridModelList);
tutorStudentsGridModelList = jtPageSize > 0 ? tutorStudentsGridModelList.Skip(jtStartIndex).Take(jtPageSize).ToList() : tutorStudentsGridModelList.ToList();
return Json(new { Result = "OK", Records = tutorStudentsGridModelList, TotalRecordCount = studentListResponse.StudentList.Count() });
}
Initially, the page with grid get loaded from server with the list of students with fields i.name ii.batch iii.email iv.contact_no, after selecting "name" from dropdown and entered a name in textbox then clicking the search button for search , the search results should display. But its displaying old grid. kindly tell me how to display the search result from the grid using jquery.

Related

DropdownList Synfuscion and ASP.NET Core not working

I am creating a syncfusion DropdownList which I want to populate with a json that I return from a controller of my Api, for this I have the following code in javascript:
<input type="text" id="groupCodeList" />
var customerList = ej.DataManager({ url: "Administration/GetGroups", adaptor: new ej.UrlAdaptor(), crossDomain: true });
$(function () {
var groupCodeList = $('#groupCodeList').ejDropDownList({
dataSource: customerList,
fields: { text: 'ID', text: 'ProductName', value: 'ProductName' },
itemsCount: 20,
popupHeight: "200px",
width: "250px",
enableFilterSearch: true,
enableServerFiltering: true,
allowVirtualScrolling: true,
search: function (args) {
if (args.searchString.length < 3) { //check search string length
args.cancel = true;
}
}
})
//.data("ejDropDownList");
//obj._updateSelectedIndexByValue = function () { }
});
I then have a C# controller that receives the data as follows:
public IActionResult GetGroups([FromBody] ExtendedDataManagerRequest dm)
{
var store = new Store();
store.Result = new List<Product>();
store.Count = 2;
var p1 = new Product();
p1.ProductName = "blabla";
p1.ID = "1";
var p2 = new Product();
p2.ProductName = "popopo";
p2.ID = "2";
store.Result.Add(p1);
store.Result.Add(p2);
store.Result.ToArray();
return Json(store);
}
For some reason the dropdownlist never puts the values and it even seems to be disabled when I try to see if it has any value.
dropdwonlist disabled
I would also like to be able to send some extra parameter to the controller when the dropdown starts (this function is being fired when the page starts)
Any ideas? Thank you!

display child grid based on parent grid

I have a requirement where I need to Display parent grid.
Based on the item selected in the parent, fetch data and display in child grid. I am currently doing a UI mockup and don't have the models all built yet. So the models you see below are just samples.
I can display the parent grid with data I need. I also have code to select a row in the parent grid and send the row data to the controller using ajax post. I need to use this data to populate the child grid. This is the step where I am not sure what I am doing wrong.
My controllers and views are below : Can you please help ?
--Controller:
public ActionResult GetData()
{
List<Hierarchy> lh = new List<Hierarchy>();
Hierarchy m = new Hierarchy();
m.Hierarchy1 = 1;
m.Hierarchy2 = 2;
m.Hierarchy3 = 3;
lh.Add(m);
Hierarchy n = new Hierarchy();
n.Hierarchy1 = 11;
n.Hierarchy2 = 22;
n.Hierarchy3 = 33;
lh.Add(n);
Hierarchy o = new Hierarchy();
o.Hierarchy1 = 111;
o.Hierarchy2 = 222;
o.Hierarchy3 = 333;
lh.Add(o);
return Json(new { rows = lh }, JsonRequestBehavior.AllowGet);
}
public ActionResult EditDescription(Hierarchy info)
{
List<Product> plist = new List<Product>();
if (info.Hierarchy1 == 1 && info.Hierarchy2 == 2 && info.Hierarchy3 == 3)
{
Product p = new Product();
p.ProductId = 1;
p.Productdesc = "ABC";
plist.Add(p);
Product q = new Product();
q.ProductId = 2;
q.Productdesc = "DEF";
plist.Add(q);
}
if (info.Hierarchy1 == 11 && info.Hierarchy2 == 22 && info.Hierarchy3 == 33)
{
Product p = new Product();
p.ProductId = 11;
p.Productdesc = "ABCD";
plist.Add(p);
Product q = new Product();
q.ProductId = 22;
q.Productdesc = "DDEF";
plist.Add(q);
}
return Json(new { rows = plist }, JsonRequestBehavior.AllowGet);
//return Json("Response from Edit");
}
View :
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<table id="jqGrid"></table>
<div id="jqGridpager"></div>
<table id="jqSubGrid"></table>
<link href="~/Content/Theme/jquery-ui.min.css" rel="stylesheet" />
<link href="~/Content/ui.jqgrid.css" rel="stylesheet" />
#section scripts{
<script src="~/Scripts/jqGrid/grid.locale-en.js"></script>
<script src="~/Scripts/jqGrid/jquery.jqGrid.js"></script>
<script>
$(function () {
$grid = $("#jqGrid").jqGrid({
url: '#Url.Action("GetData","TEST")',
mtype: 'GET',
datatype: 'json',
colModel: [
{ label: 'Hierarchy1', name: 'Hierarchy1' },
{ label: 'Hierarchy2', name: 'Hierarchy2' },
{ label: 'Hierarchy3', name: 'Hierarchy3' },
],
loadonce: true,
pager: '#jqGridPager',
rowNum: 10,
rowList: [10, 20, 30, 50],
viewrecords: true,
height: 250,
});
$("#jqGrid").jqGrid('navGrid', '#jqGridPager', { edit: false, add: false, del: false })
$("#jqGrid").jqGrid('setGridParam', {
onSelectRow: function (rowid, iRow, iCol, e) {
var rowData = $("#jqGrid").jqGrid("getRowData", rowid);
//alert(rowData.Key);
var data0 = { Hierarchy1: rowData.Hierarchy1, Hierarchy2: rowData.Hierarchy2, Hierarchy3: rowData.Hierarchy3 };
// var data0 = { numberId: "1", companyId: "531" };
// var roles = ["role1", "role2", "role3"];
jQuery.ajax({
type: "POST",
url: "#Url.Action("EditDescription")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data0),
success: function (data) {
//alert(data);
},
failure: function (errMsg) {
alert(errMsg);
}
});
$grid1 = $("#jqSubGrid").jqGrid({
url: '#Url.Action("EditDescription", "TEST")',
mtype: 'GET',
datatype: 'json',
colModel: [
{ label: 'ProductId', name: 'ProductId' },
{ label: 'Productdesc', name: 'Productdesc' },
],
loadonce: true,
pager: '#jqGridPager',
rowNum: 10,
rowList: [10, 20, 30, 50],
viewrecords: true,
height: 250,
});
}
});
});
</script>
}

Not getting stored data when navigating to next view

I am very much troubled by the thing, tat I am not able to store the user info for the next view. Here is my factory:
app.factory("currentUser", currentUser);
function currentUser() {
var profile = {
userId: "",
firstName: "",
lastName: "",
userEmailId: "",
userAccessToken: ""
};
var setProfile = function (data) {
profile.userId = "";
profile.firstName = data.userDetails.frstName;
profile.lastName = data.userDetails.lastName;
profile.userEmailId = data.Email;
profile.userAccessToken = data.userDetails.accessCode;
}
var getProfile = function () {
return profile;
}
return {
setProfile: setProfile,
getProfile: getProfile
}
}
I set the data using the function:
currentUser.setProfile(data);
But when in another controller I am trying to get the data I am getting blank object:
currentUser.getProfile();
Here is my routing
angular.module("angularModule", ["ngAnimate", "ui.router"])
.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {
// catch all route
// send users to the form page
$locationProvider.html5Mode(true);
$stateProvider.state('Register', {
url: '/Register',
templateUrl: 'Templates/Registration.html',
controller: "Registration"
})
Please help me with the solution I need the solution at earliest.
var app = angular.module("MyApp", []);
app.factory("myService", function() {
var profile = {
userId: "",
firstName: "",
lastName: "",
userEmailId: "",
userAccessToken: ""
};
profile.setProfile = function(userDetails) {
profile.userId = "";
profile.firstName = userDetails.frstName;
profile.lastName = userDetails.lastName;
profile.userEmailId = userDetails.userEmailId;
profile.userAccessToken = userDetails.accessCode;
}
profile.getProfile = function() {
return profile;
}
return profile;
});
app.controller("ctrl1", ["$scope", "myService", function($scope, myService) {
$scope.profile = {
userId: "1233",
firstName: "JOHN",
lastName: "DOE",
userEmailId: "",
userAccessToken: "314wdw"
};
myService.setProfile($scope.profile);
$scope.valueA = myService.getProfile();
}]);
app.controller("ctrl2", ["$scope", "myService", function($scope, myService) {
$scope.valueB = myService.getProfile();
}]);
DEMO

jqgrid is not loading when searching by passing javascript object to asp.net webmethod

Hi tried to load the jqgrid with json by passing javascript object. but the grid is not loading.
Below is my javascript code
oSearchParam = {
InvoiceNo: document.getElementById('txtInvoiceNumber').value,
}
var grid = $("#dataGrid")[0];
//my code
$("#dataGrid").jqGrid({
// setup custom parameter names to pass to server
prmNames: {
rows: "numRows",
page: "page",
sort: "sortField",
order: "sortOrder"
},
// add by default to avoid webmethod parameter conflicts
// postData: { oSearchParam: oSearchParam },
// setup ajax call to webmethod
datatype: function (postdata) {
$(".loading").show(); // make sure we can see loader text
$.ajax({
url: 'InvoiceSearch.aspx/GetSearchResultData',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postdata),
dataType: "json",
success: function (data, st) {
if (st == "success") {
var grid = $("#dataGrid")[0];
alert(data.d);
grid.addJSONData(JSON.parse(data.d));
}
},
error: function () {
alert("Error with AJAX callback");
}
});
},
// this is what jqGrid is looking for in json callback
jsonReader: {
root: "rows",
page: "page",
total: "totalpages",
records: "totalrecords",
cell: "cell",
id: "id", //index of the column with the PK in it
repeatitems: true
},
autowidth: true,
shrinkToFit: true,
height: 'auto',
colNames: ['InvoiceNo'],
colModel: [
{ name: 'InvoiceNo', index: 'InvoiceNo', width: 55, search: false }
],
rowNum: 10,
rowList: [10, 20, 30],
pager: jQuery("#pagingGrid"),
sortname: "InvoiceNo",
sortorder: "asc",
viewrecords: true,
caption: "Grid Title Here",
gridComplete: function () {
$(".loading").hide();
}
}).jqGrid('navGrid', '#pagingGrid', { edit: true, add: true, del: true },
{}, // default settings for edit
{}, // add
{}, // delete
{ closeOnEscape: true, closeAfterSearch: true }, //search
{}
)
And below is the webmethod
[WebMethod]
public static string GetSearchResultData(int? numRows, int? page, string sortField, string sortOrder, SearchParam oSearchParam)
{
DataTable dtInvoiceList = Mymethod();
var query = dtInvoiceList.AsEnumerable()
.Select(i => new SearchParam
{
InvoiceNo = i.Field<string>("InvoiceNo"),
// ImageId = i.Field<string>("DocID"),
InvoiceAmount = i.Field<decimal>("Amount"),
// ImageId = i.Field<string>("DocID"),
Status = i.Field<string>("Status"),
CurrentlyWith = i.Field<string>("CurrentlyWith")
}).ToList();
//--- setup calculations
int pageIndex = page ?? 1; //--- current page
int pageSize = numRows ?? 10; //--- number of rows to show per page
int totalRecords = query.Count(); //--- number of total items from query
int totalPages = (int)Math.Ceiling((decimal)totalRecords / (decimal)pageSize); //--- number of pages
var sortedRecords = query
.Skip((pageIndex - 1) * pageSize) //--- page the data
.Take(pageSize).ToList();
//--- format json
var jsonData = new
{
totalpages = totalPages, //--- number of pages
page = pageIndex, //--- current page
totalrecords = totalRecords, //--- total items
rows = (
from row1 in sortedRecords
select new
{
i = row1.ImageId,
cell = new string[] {
row1.InvoiceNo,
row1.Status,
row1.CurrentlyWith,
row1.InvoiceAmount.ToString(),
}
}
).ToArray()
};
string result = Newtonsoft.Json.JsonConvert.SerializeObject(jsonData);
return result;
}
My webmethod is not getting called.
Can anybody help me on this.

MVC 4, jTable 2.3, Table data isn't rebuilt on second (+) call

A selection on the first table results in change in the second table. However, the change occurs only once. Any subsequent calls do generate valid JSON but the html remains unchanged.
The Controller:
[HttpPost]
public JsonResult M1List(int jtStartIndex, int jtPageSize, string jtSorting)
{
try
{
List<tblM> m1 = new DataHelper().GetM1(jtSorting, jtPageSize, jtStartIndex);
int m1Count = new DataHelper().Getm1Count();
return Json(new { Result = "OK", Records = m1, TotalRecordCount = m1Count });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
[HttpPost]
public JsonResult M2List(int mId, int jtStartIndex, int jtPageSize)
{
try
{
List<ViewM1A> m2 = new DataHelper().GetM2ForM1(mId.ToString(), "mId", jtPageSize, jtStartIndex);
int m2Count = new DataHelper().GetM2ForM1Count(mId.ToString());
return Json(new { Result = "OK", Records = m2, TotalRecordCount = m2Count });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
The JS:
$(document).ready(function () {
$('#m1TC').jtable({
paging: true,
sorting: true,
defaultSorting: 'Name ASC',
selecting: true, //Enable selecting
multiselect: false, //Allow multiple selecting
actions: {
listAction: '#Url.Action("M1List")'
},
fields: {
mId: {
title: 'Id'
}
},
selectionChanged: function () {
var $selectedRows = $('#m1TC').jtable('selectedRows');
$selectedRows.each(function () {
var record = $(this).data('record');
buildM2Table(record.mId);
});
$('#m2TC').jtable('load');
}
});
$('#m1TC').jtable('load');
});
function buildM2Table(actionUrl) {
$('#m2TC').jtable({
paging: true,
sorting: true,
defaultSorting: 'Name ASC',
selecting: true, //Enable selecting
multiselect: true, //Allow multiple selecting
selectingCheckboxes: true, //Show checkboxes on first column
actions: {
listAction: '/Connections/M2List?mId=' + actionUrl
},
fields: {
FullName: {
title: 'Name'
},
},
selectionChanged: function () {
var $selectedRows = $('#m2TC').jtable('selectedRows');
$('#SelectedRowList').empty();
if ($selectedRows.length > 0) {
} else {
$('#SelectedRowList').append('No row selected! Select rows to see here...');
}
}
});
}
The html:
<div id="m1TC"></div>
<div id="m2TC"></div>
Solved by adding this code after 'var record = $(this).data("record");':
$('#m2TC').remove();
$('#m1TC').after('<div id="m2TC"></div>');

Categories

Resources