Razor asp.net: access javascript variable - c#

Currently I have this:
resources: [
{
field: "roomId",
name: "Rooms",
dataSource: {
transport: {
read: {
url: "#Html.Raw(
Url.Action(
"Filter_Rooms",
"Room",
new {
pFilter = false,
pCapacity = 25,
pBeamer = true,
pTelevision = false
}))",
dataType: "json"
},
}
}
}
]
These parameters pFilter = false, pCapacity = 25, pBeamer = true, pTelevision = false, for the filter are now hard coded but actually I want them from:
HTML
<div class="checkbox">
<label>
<input id="chkBeamer" type="checkbox"> Beamer available
</label>
</div>
Filter rooms
Javascript
$(document).ready(function () {
$("#btnFilter").click(function () {
var pFilter = document.getElementById("chkBeamer").checked;
});
});
Can I get the javascript to use the pFilter parameter instead of the hard-coded ones?
HTMLHidden
<div class="checkbox">
<label>
#Html.Hidden("pBeamer", true);
<input id="chkBeamer" type="checkbox"> Beamer available
</label>
</div>
Javascript Resources
resources: [
{
field: "roomId",
name: "Rooms",
dataSource: {
transport: {
read: {
url: "#Html.Raw(
Url.Action(
"Filter_Rooms",
"Room",
new {
pBeamer = ("#pBeamer")???
}))",
dataType: "json"
},
}
}
}
]

There are two ways in which you can do this:-
1) You can have hidden fields for each of these four fields which you can fill in your Javascript function on click of btnFilter. Access those hidden fields while using resources.
#Html.Hidden("pFilter","<value>");
You can access these hidden fields in your code below.
resources: [
{
field: "roomId",
name: "Rooms",
dataSource: {
transport: {
read: {
url: "#Html.Raw(
Url.Action(
"Filter_Rooms",
"Room",
new {
pFilter = <get value from hidden field>,
pCapacity = <get value from hidden field>,
pBeamer = <get value from hidden field>,
pTelevision = <get value from hidden field>
}))",
dataType: "json"
},
}
}
}
]
2) You can have global variables to which you assign values on btnFilter click and use it in resources as you are doing currently.
I would suggest you to follow the first solution.

Related

jqGrid not showing json data in MVC

jqGrid is not showing json data fetched from MVC controller, it also has a emptyrecords label which is also not visible in this case. Here is my jQuery code-
$(function () {
$("#JQGrid1").jqGrid({
url: "/CertificateDetails/GetCertificateDetails",
datatype: 'json',
mtype: 'Get',
colNames: ['Name', 'Issuer', 'Location', 'Private Key[Yes/No]'],
//data: dataArray,
colModel: [
{
key: false,
name: 'Name',
index: 'Name',
editable: false
},
{
key: false,
name: 'Issuer',
index: 'Issuer',
editable: false
},
{
key: false,
name: 'Location',
index: 'Location',
editable: false
},
{
key: false,
name: 'HasPrivateKey',
index: 'HasPrivateKey',
editable: false
}
],
height: '100%',
viewrecords: true,
caption: "Certificate Details",
emptyrecords: "No record to display!!"
});
});
Controller code:
CertDetails cd = new CertDetails();
public ActionResult Index()
{
return View();
}
//
// GET: /CertificateDetails/
public ActionResult GetCertificateDetails()
{
var stores = new Dictionary<StoreName, string>()
{
{StoreName.My, "Personal"},
{StoreName.Root, "Trusted roots"},
{StoreName.TrustedPublisher, "Trusted publishers"},
{StoreName.AddressBook, "Address Book"},
{StoreName.AuthRoot, "Auth Root"},
{StoreName.CertificateAuthority, "Certificate authority"},
{StoreName.Disallowed, "Disallowed"},
{StoreName.TrustedPeople, "Trusted people"}
// and so on
}.Select(s => new { store = new X509Store(s.Key, StoreLocation.LocalMachine), location = s.Value }).ToArray();
foreach (var store in stores)
store.store.Open(OpenFlags.ReadOnly); // open each store
var list = stores.SelectMany(s => s.store.Certificates.Cast<X509Certificate2>()
.Select(mCert => new CertDetails
{
HasPrivateKey = mCert.HasPrivateKey ? "Yes" : "No",
Name = mCert.FriendlyName != "" ? mCert.FriendlyName : "Unavailable",
Location = s.location,
Issuer = mCert.Issuer
})).ToList();
return Json(list,JsonRequestBehavior.AllowGet);
}
Here is the data returned from controller action method-
[{"Name":"Unavailable","HasPrivateKey":"Yes","Location":"Personal","Issuer":"CN=Dell Issuing Certificate Authority 302, OU=MS PKI, O=Dell Inc."},{"Name":"IIS Express Development Certificate","HasPrivateKey":"Yes","Location":"Personal","Issuer":"CN=localhost"}]
I'm getting the data in JSON format from the controller but neither jqGrid shows any data nor it shows empty records label. Any idea how to solve this issue?
You can try jQuery DataTable plugin instead, like below:
$(document).ready(function () {
$("#myGrid").dataTable({
"ajax": {
"url": "/CertificateDetails/GetCertificateDetails",
"dataSrc": ""
},
"columns": [{
"data": "Name"
}, {
"data": "Location"
}, {
"data": "Issuer"
}, {
"data": "HasPrivateKey"
}]
});
});
<table id="myGrid">
<thead>
<tr style="text-align:left;">
<th>Name</th>
<th>Location</th>
<th>Issuer</th>
<th>HasPrivateKey?</th>
</tr>
</thead>
</table>
Don't forget to add the references-
<link rel="stylesheet" type="text/css" href="http://cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css">
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.2.0.min.js"></script>
<script type="text/javascript" charset="utf8" src="http://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>

Issue passing value from textbox to jquery function and onto controller function

I came across an issue with passing values to jQuery where I want to pass the value from a textbox.
Here is the .cshtml:
#Html.TextBoxFor(m => m.OrderNumber, new { #class = "form-control", id = "orderNumber" })
My script:
function maintenance_tapped(e) {
var data = $('#orderNumber').val();
$("#SapPopUp")
.dialog({
width: 600,
height: 420,
model: true,
buttons: {
"OK": function() {
$.ajax({
url: '#Url.Action("RetrieveOrder", "Home")',
data: data,
type: "POST"
}).done(function() {
$(this).dialog("close");
});
},
"Cancel": function() {
$(this).dialog("close");
}
}
});
}
Code in my controller:
[HttpPost]
public async Task<ActionResult> RetrieveOrder(string number)
{
if (_sapHelper == null)
{
_sapHelper = new Helper();
}
return View();
}
My issue is that if I put a breakpoint in the RetrieveOrder function and I check the value of number i get null.
Then if go into Chrome->inspect element->Console and type $('#orderNumber').val(), I get the value I entered into the textbox.
It also seems like its not passing the value into the function.
Try this
dataType :'json',
data: {number: data},
Fixed this thanks to Aleksander Matic and Rob Lang.
Soloution
function maintenance_tapped(e) {
//var data = $('#orderNumber').val(); <------- Remove from here
$("#SapPopUp")
.dialog({
width: 600,
height: 420,
model: true,
buttons: {
"OK": function() {
var data = $('#orderNumber').val(); //<--------- Place here
$.ajax({
url: '#Url.Action("RetrieveOrder", "Home")',
data: data,
type: "POST",
dataType :'json', //<-------- Added
data: {number: data}, //<-------- Added
}).done(function() {
$(this).dialog("close");
});
},
"Cancel": function() {
$(this).dialog("close");
}
}
});
}
You can have the value in a javascript object and match the key to your action's parameter name.
This should work.
$.ajax({
url: '#Url.Action("RetrieveOrder", "Home")',
data: {
number: $('#orderNumber').val()
},
type: "POST"
}).done(function() {
$(this).dialog("close");
});
Also, I see you are returning a viewresult from the action method, but not using that in your ajax method call's done/success event handler. What is the point of doing that?

update Jquery Jtable plugin depending on a selected row in another Table

hello I have the following snippet of code.
Departments
<div>Users </div>
<div id="UserTableContainer"></div>
<script type="text/javascript">
var departmentChangeId = 1;
$(document).ready(function () {
$('#DepartmentTableContainer').jtable({
paging: true,
useBootstrap: true,
sorting: true,
selecting: true,
selectOnRowClick: true,
title: 'Departments',
actions: {
listAction: '/api/Department/GetDepartmentList',
createAction: '/api/Department/CreateDepartment',
updateAction: '/api/Department/EditDepartment',
deleteAction: '/api/Department/DeleteDepartment'
},
fields: {
ID: {
key: true,
list: false
},
TypeId: {
title: 'Department Type',
options: '/api/Department/GetDepartmentTypeList'
},
Label: {
title: 'Department'
},
},
//Register to selectionChanged event to hanlde events
selectionChanged: function () {
//Get all selected rows
var $selectedRows = $('#DepartmentTableContainer').jtable('selectedRows');
departmentChangeId = $selectedRows.data('record').ID;
//alert(departmentChangeId);
//
refresh();
}
}).jtable('load');
$('#UserTableContainer').jtable({
messages: ArabMessages, //Lozalize
paging: true,
useBootstrap: true,
sorting: true,
title: 'Employee',
actions: {
listAction: '/api/Users/GetEmployee?id=' + departmentChangeId,
updateAction: '/api/Users/EditEmployee'
},
fields: {
Id: {
key: true,
list: false
},
DepId: {
title: ' Department',
options: '/api/Department/GetDepartmentTypeList'
},
LastName: {
title: 'Name'
},
}
});
$('#UserTableContainer').jtable('load');
});
and these are the two version I use for the refresh function
first
function refresh() {
$('#UserTableContainer').jtable('reload');
}
the second
function refresh() {
$.post("/api/Users/GetEmployee", "id=" + departmentChangeId,
function (results) {
$('#UserTableContainer').jtable('reload');
}
, "json");
}
unfortunately both of them dont work
instead of when I use debugging mode I see that the /api/Users/GetEmployee is visited in both case
please try using below code in refresh function
$('#UserTableContainer').jtable('load');

JQGrid in MVC Not Loading the Grid

I have an MVC Edit View that contains Contact Information that is of course editable. In that view I want to add a section containing a JQGrid allowing the user to CRUD notes for the Contact but my grid is not loading with data nor is the method on the controller being called. Can anyone give me any insite?
View Code
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-info">
Contact Note</h3>
</div>
<div class="panel-body">
<div class="scrollableContainer" style="margin-top: -10px;">
<table id="JQGrid1"></table>
<div id="JQGrid1_pager"></div>
</div>
</div>
</div>
<script>
$("#JQGrid1").jqGrid({
url: '#Url.Action("GetNotes", "Contact")',
mtype: "GET",
datatype: "json",
page: 1,
jsonReader: { id: document.getElementById('SelectedContact_ContactID').value },
prmNames: { id: document.getElementById('SelectedContact_ContactID').value },
colNames: ["Id", "ContactId", "Note", "Date Created", "Created By"],
colModel: [
{ key: true, width: 50, name: "ID", hidden: false },
{ width: 60, name: "ContactID", hidden: false },
{ width: 460, name: "Note", hidden: false },
{ width: 160, name: "DateCreated",
formatter: "date", formatoptions: { srcformat: "m/d/Y h:i:s A", newformat: "mm-dd-yyyy" }, hidden: false },
{ width: 160, name: "CreatedBy", hidden: false },
],
height: "auto",
caption: "Notes",
rowNum: 5,
pager: "#JQGrid1_pager",
});
</script>
Controller Code
[HttpGet]
public JsonResult GetNotes(int id)
{
var gridModel = new ContactNotesJQGridModel();
var resultset = _contactNoteRepository.GetNotes(id);
return gridModel.ContactNotesGrid.DataBind(resultset.AsQueryable());
}
GridModel Class
public class ContactNotesJQGridModel
{
public JQGrid ContactNotesGrid { get; set; }
public ContactNotesJQGridModel()
{
ContactNotesGrid = new JQGrid
{
Columns = new List<JQGridColumn>()
{
new JQGridColumn {DataField = "ID", PrimaryKey = true},
new JQGridColumn {DataField = "ContactId"},
new JQGridColumn {DataField = "Note"},
new JQGridColumn {DataField = "DateCreated"},
new JQGridColumn {DataField = "CreatedBy"},
}
};
}
Then in the Edit Call for the Contact in the Contact Controller I set model.ContactNotesGrid = new ContactNotesJQGridModel GetNotes(int id) is never executed eventhough it's specified in the jquery.
You should use postData to add custom parameter to the server response:
postData: { id: 11 }
or
postData: {
id: function () {
return document.getElementById('SelectedContact_ContactID').value;
}
}
You need additionally modify the code of the server to use something like
return Json(someObjectWithReturnedData, JsonRequestBehavior.AllowGet);
I recommend you to add loadError callback to the list of jqGrid option (see the answer) and add gridview: true and autoencode: true option to jqGrid.
P.S. About the errors like "unable to get value of the property integer", "unable to get value of the property decimalSeperator". You should verify that you included locale file like i18n/grid.locale-en.js before jquery.jqGrid.min.js (see the documentation).
Try this :
Check 1:
Move your Jquery script inside the document ready event:
$( document ).ready(function() {
console.log( "ready!" );
});
Check 2:
Check weather your server request having any problem or not:
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Response.Clear();
}
Add the above code in your Global.asax and make sure there is no exception during the call. (Put Break point and check)
Check 3:
Watch your browser console log (F12). If there is any exception log please provide that.
Check 4:
Make sure if the call is success the expected json format is valid or not. In most of the cases it will be the major cause.
The above's are just my guesses / this is what i do first, if i have a prob. :)

Uncaught TypeError : cannot read property 'pager' of undefined In KendoGrid

Im trying to keep option "All" for showing all the data in grid by using following code.
but when the code reaches grid.pager.element its showing error as "pager" undefined.
at first when i click on search with group "TBU" there is no option for All.When i click again "All" appears as how many times i have clicked.
$.ajax({
type: "POST",
url: "Report_Services/Report.asmx/BindKendoAvailableList",
data: "{'groupId':" + $('#cboGroupName option:selected').val() + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
data = result.d;
$("#grid").kendoGrid({
dataSource: {
transport: {
read: function (options) {
options.success(data);
}
},
schema: {
type: "xml",
data: "/NewDataSet/myTable",
model: {
// configure the fields of the object
fields: {
AssetCode: "AssetCode/text()",
AssetName: "AssetName/text()"
AssetStatusName: "AssetStatusName/text()"
}
}
},
pageSize: 10
},
sortable: true,
filterable: true,
reorderable: true,
navigatable: true,
selectable: "multiple",
columnMenu: true,
resizable: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 8
},
columns:
[{
field: "AssetCode",
title: "Asset Id"
}, {
field: "AssetName",
title: "Asset Name"
},{
field: "AssetStatusName",
title: "Status"
}]
});
}
});
debugger;
var grid = $("#grid").data("kendoGrid");
var dropdown = grid.pager.element
.find(".k-pager-sizes [data-role=dropdownlist]")
.data("kendoDropDownList");
var item = {};
item[dropdown.options.dataTextField] = "All";
item[dropdown.options.dataValueField] = 1000000;
dropdown.dataSource.add(item);
dropdown.bind("change", function (e) {
if (this.text() == "All") {
grid.one("dataBound", function () {
setTimeout(function () {
dropdown.span.text("All");
});
});
}
});
In your case it sounds like the grid variable is undefined not the pager. Make sure that you execute this code after the Grid is actually initialized and also make sure the selector is right.

Categories