IN my Database table i have more then 30,000 records,here i am trying to Display these records in JqGrid,Here i displayed upto 900 records only, How can i display all records in JqGrid,here i am attaching my code.
<script type="text/javascript">
$(function () {
$("#dataGrid").jqGrid({
url: 'Default.aspx/GetDataFromDB',
datatype: 'json',
mtype: 'POST',
overflow:'visible',
serializeGridData: function (postData) {
return JSON.stringify(postData);
},
ajaxGridOptions: { contentType: "application/json" },
loadonce: true,
colNames: ['AOfficeKey', 'AChartNumber', 'APatientName', 'AVisit#'],
colModel: [
{ name: 'AOfficeKey', index: 'AOfficeKey', width: 80 },
{ name: 'AChartNumber', index: 'AChartNumber', width: 150 },
{ name: 'APatientName', index: 'APatientName', width: 160 },
{ name: 'AVisit#', index: 'AVisit#', width: 160 }
],
pager: '#pagingGrid',
rowNum: 100,
height: 300,
width:600,
rowList: [10, 100, 1000, 10000],
gridview: true,
viewrecords: true,
gridview: true,
jsonReader: {
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.d.length; },
root: function (obj) { return obj.d; },
repeatitems: false,
id: "0"
},
});
});
</script>
</head>
<body style="font-family: Arial; font-size: 10pt">
<table style="border: solid 1px ; width: 100%; vertical-align: central;">
<tr>
<td style="padding-left: 20px; padding-top: 20px; padding-bottom: 20px; font-family: 'Times New Roman'; font-weight: bold; font-size: 20pt; color: chocolate;">
</td>
</tr>
<tr>
<td style="text-align: center; vertical-align: central; padding: 100px;">
<table id="dataGrid" style="text-align: center; width: 100%;"></table>
<div id="pagingGrid"></div>
</td>
</tr>
</table>
C# code is
[WebMethod]
public static List<Dictionary<string, object>> GetDataFromDB()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(#"Data Source=Abc;Database=Training;User Id=sa;Password=abc;"))
{
using (SqlCommand cmd = new SqlCommand("SELECT * AOfficeKey,AChartNumber, APatientName,AVisit# from adjs", con))
//("SELECT ID,Client,Location,Address FROM AClients ", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return rows;
}
}
}
I've tried your code and it works without error. However in order to load large data from server you will need to increase allowed JSON size when using json serialization. In order to do it past following code to your web.config in the <configuration> tag:
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
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;
}
}
}
}
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 ?
no matter what i do , i am getting error in jQuery Ajax calls. Can you figure out what am I missing here?
Here is my Interface IShow
[ServiceContract]
public interface IShow
{
[OperationContract]
string getShow(int _showID);
}
Here is my Class
[DataContract]
public class Show
{
private string _title, _description;
private DateTime _showDate;
private int _showID;
[DataMember]
public string Title
{
get { return _title; }
set { _title = value; }
}
[DataMember]
public string Description
{
get { return _description; }
set { _description = value; }
}
[DataMember]
public DateTime ShowDate
{
get
{
return _showDate;
}
set { _showDate = value; }
}
[DataMember]
public int ShowID { get { return _showID; } set { _showID = value; } }
}
my Service called sShows.svc
[AspNetCompatibilityRequirements(
RequirementsMode
= AspNetCompatibilityRequirementsMode.Allowed)]
public class sShows : IShow
{
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json
)]
public string getShow(int _showID)
{
MySqlConnection Conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["CS1"].ConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = Conn;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = " SELECT s.master_id, m.showname, m.showinfo, MIN(CONCAT(s.show_date, ' ', s.show_time)) AS first_show_date, MAX(CONCAT(s.show_date, ' ', s.show_time)) AS last_show_date FROM shows s LEFT OUTER JOIN master m ON s.master_id = m.master_id WHERE (s.wt_offsale = '') AND (s.master_id = #mid) GROUP BY s.master_id ORDER BY s.show_date, s.show_time";
cmd.Parameters.AddWithValue("#mid", _showID.ToString());
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
try
{
Conn.Open();
da.Fill(dt);
Show sh = null;
if (dt.Rows.Count > 0)
{
sh = new Show
{
Title = dt.Rows[0].ItemArray[1].ToString(),
Description = dt.Rows[0].ItemArray[2].ToString()
};
}
// return sh;
return JsonConvert.SerializeObject(sh, Formatting.Indented);
}
catch (Exception)
{
throw;
}
finally
{
Conn.Close();
dt.Dispose();
da.Dispose();
}
}
}
and finally this is my web.config (In the service project)
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="WebBehaviour">
<!--<enableWebScript/>-->
<webHttp defaultOutgoingResponseFormat="Json"/>
<!--<webHttp/>-->
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
this is my Ajax Call
jQuery.ajax({
type: "POST",
url: "http://localhost:10677/sShows.svc/Web/getShow",
data: "{_showID: 288}",
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (result) {
alert(result.d.Title);
},
error: function (result) {
alert(result.statusText);
console.log("Service = " + result.d);
}
});
No matter what i do, i am getting "Error" on the client as an alert. Can you please check what exactly the issue is ???
Thanks
UPDATE
Here is what i got from fiddler
OPTIONS http://localhost:10677/sShows.svc/Web/getShow HTTP/1.1
Host: localhost:10677
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://localhost:2299
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36
Access-Control-Request-Headers: accept, content-type
Accept: */*
DNT: 1
Referer: http://localhost:2299/SimiArts/events.aspx
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8,ur;q=0.6
HTTP/1.1 405 Method Not Allowed
Cache-Control: private
Allow: POST
Content-Length: 1565
Content-Type: text/html; charset=UTF-8
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcQXRoYXJBbmlzXERvY3VtZW50c1xNRUdBXFBQSCBKb2JzXFNoYXVuXFdjZlNlcnZpY2UxXHNTaG93cy5zdmNcV2ViXGdldFNob3c=?=
X-Powered-By: ASP.NET
Date: Tue, 08 Apr 2014 16:12:24 GMT
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Service</title>
<style>BODY { color: #000000; background-color: white; font-family: Verdana; margin-left: 0px; margin-top: 0px; } #content { margin-left: 30px; font-size: .70em; padding-bottom: 2em; } A:link { color: #336699; font-weight: bold; text-decoration: underline; } A:visited { color: #6699cc; font-weight: bold; text-decoration: underline; } A:active { color: #336699; font-weight: bold; text-decoration: underline; } .heading1 { background-color: #003366; border-bottom: #336699 6px solid; color: #ffffff; font-family: Tahoma; font-size: 26px; font-weight: normal;margin: 0em 0em 10px -20px; padding-bottom: 8px; padding-left: 30px;padding-top: 16px;} pre { font-size:small; background-color: #e5e5cc; padding: 5px; font-family: Courier New; margin-top: 0px; border: 1px #f0f0e0 solid; white-space: pre-wrap; white-space: -pre-wrap; word-wrap: break-word; } table { border-collapse: collapse; border-spacing: 0px; font-family: Verdana;} table th { border-right: 2px white solid; border-bottom: 2px white solid; font-weight: bold; background-color: #cecf9c;} table td { border-right: 2px white solid; border-bottom: 2px white solid; background-color: #e5e5cc;}</style>
</head>
<body>
<div id="content">
<p class="heading1">Service</p>
<p>Method not allowed.</p>
</div>
</body>
</html>
"{_showID: 288}" is not valid JSON. "{\"_showID\": 288}" is probably what you're looking for. Or, better, create a plain object and let jQuery do the JSON serialization.
data: { _showId: 288 },
The OPTIONS call is due to the cross-site scripting call. Make the web site and service on the same host and port, or use a JSONP callback like jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox suggests.
Please find the below code for webservice. It is the post method webservice but when I am trying to parse it from iPhone. It is throwing error.
function TestMe(strURI) {
//alert(strURI);
$.ajax({
url: strURI,
type: 'POST',
//contentType: 'application/json',
data: JSON.stringify({
"Input": [
{
"MeetingId":"2",
"FromUserId":"1",
"DBMessage": "Test Message by index page"
}]
}),
success: function (result) {
alert('success');
console.log(result);
},
error: function (data) {
console.log(data);
alert('error');
},
complete: function () {
//alert('complete');
}
});
}
In other class I have defined this method
public string SaveDiscussionBoardMsg(Stream input)
{
string body = new StreamReader(input).ReadToEnd();
string strJSONResult = "";
objDAMeeting = new DA.Meeting();
BO.BMO.DiscussionBoard objBODiscussionBoard = new BO.BMO.DiscussionBoard();
//Method-2
//string JsonInsertSQL = #" {""Input"":[{""MeetingId"":1,""DBMessage"":""My Msg"",""FromUserId"":1},{""MeetingId"":1,""DBMessage"":""My Msg"",""FromUserId"":1}]}";
//string JsonInsertSQL = #" {""Input"":[{""MeetingId"":1,""DBMessage"":""My Msg"",""FromUserId"":1}]}";
dynamic dynObj = Newtonsoft.Json.JsonConvert.DeserializeObject(body);
foreach (var item in dynObj.Input)
{
objBODiscussionBoard.MeetingId = Convert.ToInt32(item.MeetingId.ToString());
objBODiscussionBoard.DBMessage = item.DBMessage.ToString();
objBODiscussionBoard.FromUserId = Convert.ToInt32(item.FromUserId.ToString());
strJSONResult = objDAMeeting.SaveDiscussionBoardMsg(objBODiscussionBoard);
}
strJSONResult = string.Format("{0}{1}{2}", strPrefix, "\"" + strJSONResult + "\"", strPostfix);
//HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
//HttpContext.Current.Response.Write(strJSONResult);
objDAMeeting = null;
return strJSONResult;
}
We are using WCF
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "/SaveDiscussionBoardMsg")]
string SaveDiscussionBoardMsg(Stream input);
I am getting this error. Please find below error.
{
html = {
body = {
div = {
"div##Attributes##" = {
id = content;
};
p = (
"Request Error",
{
a = "service help page";
"p##Attributes##" = {
xmlns = "";
};
}
);
};
};
head = {
style = "BODY { color: #000000; background-color: white; font-family: Verdana; margin-left: 0px; margin-top: 0px; } #content { margin-left: 30px; font-size: .70em; padding-bottom: 2em; } A:link { color: #336699; font-weight: bold; text-decoration: underline; } A:visited { color: #6699cc; font-weight: bold; text-decoration: underline; } A:active { color: #336699; font-weight: bold; text-decoration: underline; } .heading1 { background-color: #003366; border-bottom: #336699 6px solid; color: #ffffff; font-family: Tahoma; font-size: 26px; font-weight: normal;margin: 0em 0em 10px -20px; padding-bottom: 8px; padding-left: 30px;padding-top: 16px;} pre { font-size:small; background-color: #e5e5cc; padding: 5px; font-family: Courier New; margin-top: 0px; border: 1px #f0f0e0 solid; white-space: pre-wrap; white-space: -pre-wrap; word-wrap: break-word; } table { border-collapse: collapse; border-spacing: 0px; font-family: Verdana;} table th { border-right: 2px white solid; border-bottom: 2px white solid; font-weight: bold; background-color: #cecf9c;} table td { border-right: 2px white solid; border-bottom: 2px white solid; background-color: #e5e5cc;}";
title = "Request Error";
};
"html##Attributes##" = {
xmlns = "http://www.w3.org/1999/xhtml";
};
};
}
Try after adding dataType: 'json' as
$.ajax({
url: strURI,
type: 'POST',
dataType: 'json',
//contentType: 'application/json',
data: JSON.stringify({
"Input": [
{
"MeetingId":"2",
"FromUserId":"1",
"DBMessage": "Test Message by index page"
}]
}),
success: function (result) {
alert('success');
console.log(result);
},
error: function (data) {
console.log(data);
alert('error');
},
complete: function () {
//alert('complete');
}
});
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>