My image viewer :
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link rel="stylesheet" type="text/css" href="http://cdn.sencha.com/ext/gpl/5.1.0/build/packages/ext-theme-classic/build/resources/ext-theme-classic-all.css">
<script type="text/javascript" src="http://cdn.sencha.com/ext/gpl/5.1.0/build/ext-all.js"></script>
<script type="text/javascript" src="http://cdn.sencha.com/ext/gpl/5.1.0/build/packages/ext-theme-classic/build/ext-theme-classic.js"></script>
<style>
.thumbnail {
padding: 4px;
background-color: #e6e6e0;
border: 1px solid #d6d6d0;
float: left;
margin-right: 10px;
margin-bottom: 10px;
cursor: pointer;
}
</style>
</head>
<body>
<script>
Ext.define('Image', {
extend: 'Ext.data.Model',
fields: [
{ name: 'href', type: 'string' },
{ name: 'caption', type: 'string' }
]
});
var imagesStore = Ext.create('Ext.data.Store', {
id: 'imagesStore',
model: 'Image',
data: [
{ href: 'images/Hydrangeas.jpg', caption: 'Hydrangeas' },
{ href: 'images/Jellyfish.jpg', caption: 'Jellyfish' },
{ href: 'images/Koala.jpg', caption: 'Koala' },
{ href: 'images/Lighthouse.jpg', caption: 'Lighthouse' }
]
});
var imageTpl = new Ext.XTemplate(
'<tpl for=".">',
'<div class="thumbnail" onClick="javascript:openWindow(this.lightbox);" >',
'<img src="{href}" width="200px" height="150px" />',
'<br/><span>{caption}</span>',
'</div>',
'</tpl>'
);
var sel_thumb_id = 0;
var thumbs = Ext.create('Ext.view.View', {
id: 'thumbs',
store: Ext.data.StoreManager.lookup('imagesStore'),
tpl: imageTpl,
itemSelector: 'img',
emptyText: 'No images available',
renderTo: document.body,
listeners: {
}
});
var img = Ext.create('Ext.Img', {
id:'img',
src: '',
shrinkWrap: true
});
var next = Ext.create('Ext.Button', {
xtype: 'button',
text: 'Next',
width: 100,
handler: function () {
if (img_id < imagesStore.data.items.length ) {
img_id = img_id + 1;
var nextSrc = imagesStore.data.items[img_id].data.href;
console.log(nextSrc);
Ext.getCmp('img').setSrc(nextSrc);
}
}
});
var previous = Ext.create('Ext.Button', {
xtype: 'button',
text: 'Previous',
width: 100,
handler: function () {
if (img_id > 0) {
img_id = img_id - 1;
var nextSrc = imagesStore.data.items[img_id].data.href;
Ext.getCmp('img').setSrc(nextSrc);
}
}
});
var lightbox = new Ext.window.Window( {
id: 'lightbox',
title: '',
height: 600,
width: 800,
layout: 'fit',
items: [img],
modal: true,
draggable: false,
dockedItems: [{
xtype: 'toolbar',
dock: 'bottom',
padding: '5 20',
align: 'center',
items: [previous, next]
}],
closeAction: 'hide',
resizable: false
})
function openWindow(lightbox) {
img.setSrc('images/Hydrangeas.jpg');
Ext.getCmp('lightbox').show();
img_id = 0;
}
</script>
</body>
In this way, images are stored in a folder. Now i want to load images from database. I don't mean image path from database, i mean image. I can get images data from database using c# asmx web service.
1) What type should i choose to store images in ms sql ?
2) How can i convert data that i will get from database and display as images ?
Related
I want to save my coordinates from the frontend to the backend and I don't know how to send them.
the coordinates are saved in a JS array and I don't know how to transfer them to C#.
HTML, CSS & JS for the map
<link rel="stylesheet" href="~/css/ol.css">
<link rel="stylesheet" href="~/css/ol-ext.css">
<script src="~/js/ol.js"></script>
<script src="~/js/ol-ext.js"></script>
#*<script src="~/js/elm-pep"></script>*#
#*<script src="~/js/JavaScript.js"></script>*#
<div id="map" style="width:600px; height:400px;">
<div class="photon ol-search ol-unselectable ol-control ol-collapsed">
<input asp-for="coordinates" type="search" class="search" autocomplete="off" placeholder="Search...">
<input asp-for="coordinates" type="button" class="ol-revers" title="click on the map">
<ul class="autocomplete history">
<li data-search="0"> 398<i> 9350004 Jérusalem (Israël)</i></li>
<li class="copy">© OpenStreetMap contributors</li>
</ul>
</div>
</div>
<div class="button-70" style="z-index:1;" id="location-button">
#*<button id="location-button" title="Get your location"></button>*#
#*<button asp-for="coordinates" class="button-70" id="location-button" role="button" title="Get your current location">📍 Get cuttent location</button>*#
<input asp-for="coordinates" type="button" value="📍 Get cuttent location" id="location-button" />
</div>
<style>
.button-70 #location-button {
background: none;
border: none;
transform: scale(2)
}
.button-70 {
transform: scale(0.7);
background-image: linear-gradient(#0dccea, #0d70ea);
border: 0;
border-radius: 4px;
box-shadow: rgba(0, 0, 0, .3) 0 5px 15px;
box-sizing: border-box;
color: #fff;
cursor: pointer;
font-family: Montserrat,sans-serif;
font-size: .9em;
margin: 5px;
padding: 10px 15px;
text-align: center;
user-select: none;
-webkit-user-select: none;
touch-action: manipulation;
}
</style>
<script type="text/javascript">
var layers = [new ol.layer.Tile({ source: new ol.source.OSM() })];
var map = new ol.Map({
target: 'map',
view: new ol.View({
zoom: 5,
center: [166326, 5992663]
}),
interactions: ol.interaction.defaults({ altShiftDragRotate: false, pinchRotate: false }),
layers: layers
});
var search = new ol.control.SearchPhoton({
lang: "fr",
reverse: true,
position: true
});
map.addControl(search);
var markers;
search.on('select', function (e) {
map.getView().animate({
center: e.coordinate,
zoom: Math.max(map.getView().getZoom(), 16)
});
loc(e.coordinate);
});
function loc(e) {
console.log(e);
if (markers) {
map.removeLayer(markers)
}
markers = new ol.layer.Vector({
source: new ol.source.Vector(),
style: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 1],
src: 'https://ucarecdn.com/4b516de9-d43d-4b75-9f0f-ab0916bd85eb/marker.png' // => https://app.uploadcare.com/projects/c05bbeb5e1a61e862903/files/7110cd57-b0ee-4833-bcd1-ff0343dd01cc/?limit=100&ordering=-datetime_uploaded
})
})
});
map.addLayer(markers);
var marker = new ol.Feature(new ol.geom.Point(e));
markers.getSource().addFeature(marker);
}
const options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
document.querySelector("#location-button").addEventListener("click", function (e) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
console.log(e);
if (markers) {
map.removeLayer(markers)
}
markers = new ol.layer.Vector({
source: new ol.source.Vector(),
style: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 1],
src: 'https://ucarecdn.com/4b516de9-d43d-4b75-9f0f-ab0916bd85eb/marker.png' // => https://app.uploadcare.com/projects/c05bbeb5e1a61e862903/files/7110cd57-b0ee-4833-bcd1-ff0343dd01cc/?limit=100&ordering=-datetime_uploaded
})
})
});
map.addLayer(markers);
function success(pos) {
const crd = pos.coords;
console.log('Your current position is:');
console.log(`Latitude : ${crd.latitude}`);
console.log(`Longitude: ${crd.longitude}`);
console.log(`More or less ${crd.accuracy} meters.`);
return new Array(crd.latitude, crd.longitude);
}
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
navigator.geolocation.getCurrentPosition(success, error, options);
var marker = new ol.Feature(new ol.geom.Point(ol.proj.fromLonLat([position.coords.latitude, position.coords.longitude])));
markers.getSource().addFeature(marker);
});
}
else {
alert("Your browser does not support geolocation");
}
});
</script>
I tried to save the coordinates in A list and in a string, but none worked.
here is the Model code:
public class ReportModel
{
//...stuff...
public string coordinates { get; set; }
//...more stuff...
}
ReportDAO.cs - Saves the given data form the user
using Microsoft.Data.SqlClient;
using SvivaTeamVersion3.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SvivaTeamVersion3.Services
{
public class ReportDAO
{
static readonly string connectionString = #"KEY";
public static bool addReport(ReportModel report)
{
bool success = false;
string sqlStatement = "INSERT INTO dbo.Reports (category,title,description,statUrgence,cordsLat,cordsLong) VALUES (#category,#title,#description,#statUrgence,#cordsLat,#cordsLong)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(sqlStatement, connection);
command.Parameters.Add("#category", System.Data.SqlDbType.NChar, 32).Value = report.category;
command.Parameters.Add("#title", System.Data.SqlDbType.NChar, 32).Value = report.title;
command.Parameters.Add("#description", System.Data.SqlDbType.NVarChar, -1).Value = report.remarks;
command.Parameters.Add("#statUrgence", System.Data.SqlDbType.NVarChar, -1).Value = report.statUrgence;
command.Parameters.Add("#cordsLat", System.Data.SqlDbType.Float).Value = report.coordinates;
command.Parameters.Add("#cordsLong", System.Data.SqlDbType.Float).Value = 0;
//I've tried to merge the lat and long to a single string, didn't work.
try
{
connection.Open();
command.ExecuteNonQuery();
success = true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return success;
}
}
}
}
Webchat version: 4.15.1 using CDN,
Description: I am using HeroCards with postback buttons but they show the text in the value after I click them, It also happens with SuggestedActions. Since in some cases I am using special codes I need to hide them from the user
Code of the cards:
private async Task<DialogTurnResult> ProcesarEnvioMenu(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
var tarjetaNecesitoPrueba = new HeroCard()
{
Buttons = new List<CardAction>()
{
new CardAction()
{
Title = "Pruebas",
Type = ActionTypes.PostBack,
Value = "Pruebas"
}
},
Images = new List<CardImage>()
{
new CardImage()
{
Url="https://chatbotfcsblobstorage2.blob.core.windows.net/imagenes/63de5d7e-bf00-498f-bb1a-84c16feef299.png"
}
},
Title = "Necesito una prueba diagnóstica ",
Subtitle = "para saber si tengo COVID"
}.ToAttachment();
var mensaje = stepContext.Context.Activity.CreateReply($"Por favor elige la opción que deseas o si lo prefieres hazme una pregunta directamente.");
mensaje.Attachments = new List<Attachment>();
mensaje.AttachmentLayout = AttachmentLayoutTypes.Carousel;
mensaje.Attachments.Add(tarjetaNecesitoPrueba);
await stepContext.Context.SendActivityAsync(mensaje, cancellationToken: cancellationToken);
return await stepContext.EndDialogAsync();
}
Code of the webchat:
<!DOCTYPE html> <html> <head>
<script src="https://cdn.botframework.com/botframework-webchat/4.15.1/webchat.js"></script>
<style>
html,
body {
height: 100%;
}
body {
margin: 0;
}
#webchat {
height: 100%;
width: 100%;
}
</style> </head> <body>
<div id="webchat" role="main"></div>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script>
const styleSet = window.WebChat.createStyleSet({
rootHeight: '100%',
rootWidth: '100%',
bubbleFromUserBackground: '#EA431C',
bubbleFromUserBorderRadius: 15,
bubbleFromUserBorderColor: '#EA431C',
bubbleFromUserTextColor: 'White',
bubbleBackground: '#24B5B1',
bubbleBorderRadius: 15,
bubbleBorderColor: '#24B5B1',
bubbleTextColor: 'White',
sendBoxButtonColor: '#0063B1',
sendBoxBorderBottom: 'solid 1px #006FBA',
sendBoxBorderLeft: 'solid 1px #006FBA',
sendBoxBorderRight: 'solid 1px #006FBA',
sendBoxBorderTop: 'solid 1px #006FBA',
suggestedActionBackgroundColor: '#EA431C',
suggestedActionBorderColor: '#EA431C',
suggestedActionBorderColor: 'White',
suggestedActionTextColor: 'White',
suggestedActionBorderStyle: 'none',
suggestedActionBorderRadius: 5,
});
styleSet.textContent = {
...styleSet.textContent,
fontFamily: "'Gotham', 'Calibri', 'Helvetica Neue', 'Arial', 'sans-serif'",
fontColor: 'White'
};
const avatarOptions = {
botAvatarBackgroundColor: '#FE9913',
botAvatarImage: 'https://wikiaprendofcscontainer.blob.core.windows.net/imagenes/wikiaprendo/logowikiaprendofcs.png',
botAvatarInitials: 'BF',
hideUploadButton: true,
};
(async function () {
const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
dispatch({
type: 'WEB_CHAT/SEND_EVENT',
payload: {
name: 'webchat/join'
}
});
}
return next(action); });
const token = '#ViewBag.Token';
var d1 = window.WebChat.createDirectLine({ token })
window.WebChat.renderWebChat({
directLine: Object.assign({}, d1, {
postActivity: activity => {
var newActivity = Object.assign({}, activity, { channelData: { "MonitorId": "#ViewBag.IdMonitor" } });
return d1.postActivity(newActivity);
}
}),
styleSet,
styleOptions:avatarOptions,
store,
sendTypingIndicator:true
}, document.getElementById('webchat'));
document.querySelector('#webchat > *').focus();
})().catch(err => console.error(err));
</script> </body> </html>
The error was in the webchat configuration on the html file. This is the right way of having a welcome message AND passing arguments to a chatbot in the channel data
(async function () {
const token = '#ViewBag.Token';
var d1 = window.WebChat.createDirectLine({ token });
const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
dispatch({
type: 'WEB_CHAT/SEND_EVENT',
payload: {
name: 'webchat/join',
value: { language: window.navigator.language }
}
});
}
if (action.type === 'DIRECT_LINE/POST_ACTIVITY') {
action = window.simpleUpdateIn(
action,
['payload', 'activity', 'channelData', 'MonitorId'],
() => '#ViewBag.IdMonitor'
);
}
return next(action);
});
window.WebChat.renderWebChat(
{
directLine: window.WebChat.createDirectLine({ token }),
store,
styleSet,
styleOptions: avatarOptions
},
document.getElementById('webchat')
);
document.querySelector('#webchat > *').focus();
})().catch(err => console.error(err));
I want to load all the events from the database in the calendar as the page loads but it's not working. Thedata is comming to the page from database but the object is not showing events.
My model is
public class Calendar
{
public int id { get; set; }
public string title { get; set; }
public DateTime starttime { get; set; }
public DateTime endtime { get; set; }
}
My controller methods are
[HttpPost]
public JsonResult dataReceiver(string title)
{
Calendar calendar = new Calendar();
calendar.title = title;
calendar.starttime = DateTime.UtcNow.ToLocalTime();
calendar.endtime = DateTime.UtcNow.ToLocalTime().AddDays(5);
db.Calendars.Add(calendar);
db.SaveChanges();
return Json(title, JsonRequestBehavior.AllowGet);
}
public ActionResult datasender()
{
var search = from m in db.Calendars select m;
//ViewBag.Message = search.ToList();
return Json(search.ToList(),JsonRequestBehavior.AllowGet);
}
and my view is
<html>
<head>
<title> Calendar</title>
<link href="~/Content/calendar/fullcalendar.css" rel="stylesheet" />
<link href="~/Content/calendar/fullcalendar.print.css" rel="stylesheet" media='print' />
<link href="~/Content/jquery-ui.min.css" rel="stylesheet" />
<style>
body {
margin: 40px 10px;
padding: 0;
font-family: "Lucida Grande",Helvetica,Arial,Verdana,sans-serif;
font-size: 14px;
}
#calendar {
max-width: 900px;
margin: 0 auto;
}
.fc-ltr {
background: #ddba8f;
}
.fc-toolbar {
background: #c64343;
}
</style>
</head>
<body>
<div id='calendar' style="height:90%; width:90%; color:black; border:1px solid blue; margin-top:5%; position:relative">
</div>
</body>
</html>
#section scripts
{
<script src="~/Scripts/calendar/moment.min.js"></script>
<script src="~/Scripts/calendar/jquery.min.js"></script>
<script src="~/Scripts/calendar/fullcalendar.js"></script>
<script src="~/Scripts/calendar/jquery-ui.custom.min.js"></script>
<script>
$(document).ready(function () {
calendarcreate();
var obj;
});
function calendarcreate() {
$.ajax({
type: "Post",
url: "/Calendar/datasender",
dataType: "html",
data: {},
success: function (data) {
obj = JSON.parse(data);
alert("successfull data received " + JSON.stringify(obj));
var cal = $('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '2015-02-12',
selectable: true,
selectHelper: true,
select: function (start, end) {
var title = prompt('Event Title:');
var eventData;
if (title) {
eventData = {
title: title,
start: start,
end: end
};
$('#calendar').fullCalendar('renderEvent', eventData, true); // stick? = true
}
$('#calendar').fullCalendar('unselect');
$.ajax({
type: "Post",
url: "/Calendar/dataReceiver",
dataType: "json",
data: { "title": eventData.title },
success: function (data) {
alert("successfull data send " + data);
},
error: function (req, status, error) {
alert(error + req + status);
}
});
},
eventClick: function (calEvent, jsEvent, view) {
alert(calEvent.title + calEvent.start + calEvent.end +obj)
},
dragOpacity: .50,
dragRevertDuration: 1000,
eventColor: '#378006',
eventBackgroundColor: 'gray',
editable: true,
eventStartEditable: true,
eventDurationEditable: true,
dragScroll: true,
eventOverlap: false,
eventLimit: true, // allow "more" link when too many events
events:
[
{
title: 'All Day Event',
start: '2015-02-01'
},
{
id: 999,
title: 'Repeating Event',
start: '2015-02-09T16:00:00'
},
{
title: 'Click for Google',
url: 'http://google.com/',
start: '2015-02-28'
}
]
});
},
error: function (req, status, error) {
alert(error + req + status);
var div = $('#SearchItemDiv');
div.html("");
div.append('Error');
}
});
}
</script>
function calendarcreate() {
$.ajax({
type: "Post",
url: "/Calendar/datasender",
dataType: "html",
data: {},
success: function (data) {
$.each(data, function (i, item)
{
item.start = new Date(item.start);
item.end = new Date(item.end);
});
obj = JSON.parse(data);
alert("successfull data received " + JSON.stringify(obj));
var cal = $('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '2015-02-12',
selectable: true,
selectHelper: true,
select: function (start, end) {
var title = prompt('Event Title:');
var eventData;
if (title) {
eventData = {
title: title,
start: start,
end: end
};
$('#calendar').fullCalendar('renderEvent', eventData, true); // stick? = true
}
$('#calendar').fullCalendar('unselect');
$.ajax({
type: "Post",
url: "/Calendar/dataReceiver",
dataType: "json",
data: { "title": eventData.title },
success: function (data) {
alert("successfull data send " + data);
},
error: function (req, status, error) {
alert(error + req + status);
}
});
},
eventClick: function (calEvent, jsEvent, view) {
alert(calEvent.title + calEvent.start + calEvent.end +obj)
},
dragOpacity: .50,
dragRevertDuration: 1000,
eventColor: '#378006',
eventBackgroundColor: 'gray',
editable: true,
eventStartEditable: true,
eventDurationEditable: true,
dragScroll: true,
eventOverlap: false,
eventLimit: true, // allow "more" link when too many events
events:
[
{
title: 'All Day Event',
start: '2015-02-01'
},
{
id: 999,
title: 'Repeating Event',
start: '2015-02-09T16:00:00'
},
{
title: 'Click for Google',
url: 'http://google.com/',
start: '2015-02-28'
}
]
});
},
error: function (req, status, error) {
alert(error + req + status);
var div = $('#SearchItemDiv');
div.html("");
div.append('Error');
}
});
}
Just added following line in questions and calendar renders:
$.each(data, function (i, item)
{
item.start = new Date(item.start);
item.end = new Date(item.end);
});
I am new to C# and ASP.NET MVC and specially views.
I have the following problem
I have this code
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult ManageEmployee(int cntID, string command)
{
//repository = new ContactRepository();
cntadrRepository = new ContactAddressCountryRepository();
//addressRepository = new AddressRepository();
if (!String.IsNullOrEmpty(command) && command.Equals("edit"))
{
var cdrcnts = cntadrRepository.GetById(cntID);
ViewBag.IsUpdate = true;
//return View("_ManageEmployee", cdrcnts);
return View("Index", cdrcnts);
//return View("Index");
}
else
{
ViewBag.IsUpdate = false;
//return View("_ManageEmployee");
return View("Index");
}
}
that returns my form empty when I click on Add button
when I click on Add I get the form slide in and the grid slide out and I can enter a new record and then after clicking on save I return to my grid with the new record.
Now the problem is When I click on Edit I have the view with only an Add button that when I click on I get the result that I want to get, directly, when I click on Edit which is the form filled with the required information
I think that I have a problem when I return the view.
What I want is that I return that form populated with the contact information when I click on Edit and stay in the same page that shows again the grid and the edited record and not have that empty page with the Add button that I need to click on again to have the required result.
Thank you for your help.
<script type="text/javascript">
$.ig.loader({
scriptPath: './js/',
cssPath: './css/',
resources: 'igGrid.*',
ready: function () {
$.getJSON("Home/GetAll", null, function (data) {
var headerTextValues = ["Relation to Will maker", "First Name", "Last Name","","",""];
$('#employeeGrid').igGrid({
expandCollapseAnimations: true,
animationDuration: 1000,
expandTooltip: "Expand to View Details",
collapseTooltip: "Hide details",
height: "400px",
width: "800px",
dataSource: data,
responseDataKey: "Records",
//dataSourceType: "json",
autoGenerateLayouts: false,
autoGenerateColumns: false,
rowEditDialogContainment: "owner",
showReadonlyEditors: false,
columns: [
{ headerText: headerTextValues[0], key: "cntID", width: 200 },
{ headerText: headerTextValues[1], key: "cntFirstName", width: 175 },
{ headerText: headerTextValues[2], key: "cntLastName", width: 175 },
//{ headerText: headerTextValues[3], key: "Age", width: 175 },
{ headerText: headerTextValues[4], key: "UpdateRow", width: 110, template: "<a href='Home/ManageEmployee?cntID=${cntID}&command=edit' class='editDialog'>Edit</a>" },
{ headerText: headerTextValues[5], key: "DeleteRow", width: 50, template: "<a href='Home/Delete?cntID=${cntID}' class='confirmDialog'><button>Delete</button></a>" },
],
initialDataBindDepth: -1,
primaryKey: 'cntID',
width: '800',
updateURL: "Home/Update",
/*columnLayouts: [
{
key: "cntD",
responseDataKey: "Records",
autoGenerateColumns: false,
autoGenerateLayouts: false,
generateCompactJSONResponse: false,
primaryKey: "cntID",
foreignKey: "cntAddressID",
columns: [
{ key: "cntId", headerText: "Address Id", width: "150px" },
{ key: "cntAddressID", headerText: "Address", width: "150px" },
//{ key: "Street", headerText: "Street", width: "150px" },
//{ key: "City", headerText: "City", width: "150px" },
//{ key: "Zip", headerText: "Zip", width: "150px" }
]
}
],*/
features: [
{
name: "Selection",
mode: "row",
multipleSelection: false
},
{
name: 'Hiding'
},
{
name: 'Paging',
type: 'local',
pageSize: 10,
inherit: true
},
{
name: 'Filtering'
},
{
name: "ColumnMoving",
mode: "immediate",
//columnDragStart: function (event, ui) {
// ui.owner.element.find('tr td:nth-child(' + (ui.columnIndex + 1) + ')').addClass("ui-state-moving");
// colMovingKey = ui.columnKey;
//},
//columnDragEnd: function (event, ui) {
// var grid = $(event.target).data('igGrid');
// var newindex = grid.options.columns.indexOf(grid.columnByKey(colMovingKey)) + 1;
// grid.element.find('tr td:nth-child(' + newindex + ')').removeClass("ui-state-moving");
//},
addMovingDropdown: true,
mode: "deferred",
type: "render"
}
],
});
});
}
});
$(document).ready(function () {
$.ajaxSetup({ cache: false });
$(".editDialog").live("click", function (e) {
e.preventDefault();
var url = $(this).attr('href');
$("#dialog-edit").load(url);
$("#dialog-edit").toggle("slide");
});
$("#openDialog").live("click", function (e) {
e.preventDefault();
var url = $(this).attr('href');
$("#dialog-create").load(url);
$("#dialog-create").toggle("slide");
})
});
</script>
#section featured {
<section class="featured">
<div class="overlap">
<div class="content-wrapper">
<!-- the igHierarchicalGrid target element-->
<table id="employeeGrid" style="width: auto;"></table>
<p>
<a id='openDialog' href='Home/ManageEmployee?cntID=0&command=create' class='openDialog ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only' style="color: white;">Add Employee</a>
</p>
<div id="btn">
<button id="add">Add</button>
</div>
I have to use jQuery grid to load data in mvc3. But I can't get rid of this error.
Inside Layout.cshtml
<link type="text/css" href="#Url.Content("~/Content/jquery-ui-titoms.css")" rel="stylesheet" />
<link type="text/css" href="#Url.Content("~/Content/ui.jqgrid.css")" rel="stylesheet" />
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery-1.7.1.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery-ui-1.8.16.custom.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery-ui-timepicker-addon.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery-ui-sliderAccess.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/grid.locale-en.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.jqGrid.min.js")"></script>
Inside Index.cshtml
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
url: '#Url.Content("~/Device/LoadDevice")',
datatype: 'json',
mtype: 'POST',
colNames: ['LoginID', 'Name', 'Model'],
colModel: [
{ name: 'LoginID', index: 'LoginID', width: 40, align: 'left' },
{ name: 'Name', index: 'Name', width: 40, align: 'Name' },
{ name: 'Model', index: 'Model', width: 400, align: 'Model'}],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'Name',
sortorder: "desc",
viewrecords: true,
imgpath: '',
caption: 'Device list'
});
});
</script>
<table id="list" class="scroll" cellpadding="0" cellspacing="0"></table>
<div id="pager" class="scroll" style="text-align:center;"></div>
Inside DeviceController
public JsonResult LoadDevice(string sidx, string sord, int page, int rows)
{
using (Dbase titoms = new Dbase())
{
var context = titoms;
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
int totalRecords = context.devices.Count();
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
var devices = context.devices.OrderBy(sidx + " " + sord).Skip(pageIndex * pageSize).Take(pageSize);
var sorted = (from item in devices
select new
{
i = item.DeviceID,
cell = new string[] { item.LoginID, item.Name, item.Model }
}).ToArray();
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = sorted
};
return Json(jsonData);
}
}
Here is the preview of the page:
LoginID, Name & Model as string in type while DeviceID is a long type.
I'm using entity framework.
Now I can't find why the such error exist, hope someone could help.. Thanks a lot.
EDIT
Thanks to Nicholas, your answer worked, but I have to change some code. This should work now:
var devices = context.devices.OrderBy("it." + sidx + " " + sord).Skip(pageIndex * pageSize).Take(pageSize);
var sorted = (from item in devices
select new
{
i = item.DeviceID,
cell = new List<string> { item.LoginID, item.Name, item.Model }
}).ToArray();
The issue is due to the specifying of your order by criteria at runtime.
You will need to change it to follow the convention
ObjectQuery<Product> productQuery2 =
productQuery1.OrderBy("it.ProductID");
So your query would be something like
var devices = context.devices.OrderBy("it." + sidx)
see this other question