get data from database using Json for search method - c#

i have a issue , my problem is it i can't use my object form my model using EF , i need this method for a autocomplete search;
this is my error message :
"The System.NotSupportedException exception occurred HResult = 0x80131515 Message = The entity type or complex type 'PizzaTn.Context.ViewModels' cannot be built in a LINQ to Entities query. Source = Procedure call tree:
public JsonResult GetSearchValue(string search)
{
PizzaTnContext db = new PizzaTnContext();
List<VilleModels> allsearch = new List<VilleModels>();
allsearch = db.Villes.Where(x => x.VilleName.Contains(search)).Select(x => new VilleModels
{
IdVille = x.IdVille,
VilleName = x.VilleName
}).ToList();
return new JsonResult { Data = allsearch, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
this my HTML
<script>
$("#searchInput").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("GetSearchValue", "Home")',
datatype: "json",
data: {
search: $("#searchInput").val()
},
success: function (data) {
response($.map(data, function (item) {
return { label: item.VilleName, value: item.VilleName };
}
)
);
},
error: function (xhr, status, error) {
alert("error");
}
});
}
});
</script>

the solution is to add an argumant .AsEnumerable() .. thanks George:
db.Villes.Where(x => x.VilleName.Contains(search)).AsEnumerable().Select(x => new VilleModels { IdVille = x.IdVille, VilleName = x.VilleName }).ToList();

Related

Internal Server Error when calling ajax post method

I'm facing problem with calling ajax POST method, it just returns error with message: Internal Server Error.
My script looks like this:
$('.add-column').click(function () {
var ids = [];
$('#table1 > tbody > tr.selected').each(function () {
var ident = $(this).attr('id');
ids.push(ident);
});
$.ajax({
url: '/Syzyf/AddUserColumns',
type: 'POST',
contentType: "application/json; charset=utf-8",
data: { id : JSON.stringify(ids) },
cache: false,
success: function (result) {
},
error: function (xhr, status, error) {
console.log(error);
}
});
});
And controller's method:
[HttpPost]
public ActionResult AddUserColumns(List<int> ids)
{
var userId = GetUserId(User.Identity.Name);
using (var ctx = new SyzyfContext())
{
foreach (var id in ids)
{
var uc = new UserColumns();
uc.ColumnId = id;
uc.UserId = userId;
ctx.UserColumns.Add(uc);
}
ctx.SaveChanges();
}
return Json("Success");
}
I thought that it may be problem with data, but when I've changed method to call ajax function foreach id in ids, It returned same error. What do I do wrong ?
EDIT
I've found solution.
The problem was with Database Table, it did not have PRIMARY KEY...

json ajax call returning success with 200 OK but goes to error with Invalid character

my project is an MVC Web application I am using ajax call to get a huge list of data as JSON.
Here is the code( i am not sure what I a missing ):
$.ajax({
url: url, //server
type: "POST",
async: true,
data: { id: id },
dataType: "json",
success: function (data) {
debugger;
jQuery.each(data, function (i, val) {
//Success code
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
window.baseShowModalOkCancel("<p>Backlog Data</p>", "<p>Error in Database</p>", "ERROR");
}
});
}
Action Controller:( This is a post method in return statement I can see the list of object with the data.
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetBacklogWithData(string id)
{
using (var db = new LiensTrackerEntities())
{
List<BackLogDataList> backLogData = new List<BackLogDataList>();
List<BackLogData> backLog;
backLog = db.BackLogDatas.OrderBy(x =>x.CaseNumber).ToList();
foreach (var item in backLog)
{
BackLogDataList backLogDataList = new BackLogDataList
{
FileNo = item.FileNo,
BackLogId = item.BackLogID,
FirstName = item.FirstName,
LastName = item.LastName,
Middle = item.Middle,
Suffix = item.Suffix,
Address = item.Address,
Address2 = item.Address2,
City = item.City,
St = item.ST,
Zip = item.SP1ZIP,
AmaesRecordCreatedDate = item.AMAESRecordCreatedDate != null ? item.AMAESRecordCreatedDate.ToString().Split(' ')[0] : null,
AddedInRecipient = item.AddedInRecipient
};
backLogData.Add(backLogDataList);
}
}
return Json(backLogData, JsonRequestBehavior.AllowGet);
}
}
It returns with 200 ok but execute the error function when i look into console i found the following error:
Thee error is due to max json string length. the solution is
MaxJsonLength exception in ASP.NET MVC during JavaScriptSerializer

Bings Maps - Read GeoJSON

I am working with the Bing Maps v8 API, trying to load my own GeoJSON onto a Bing Maps as in this example: https://www.bing.com/api/maps/sdkrelease/mapcontrol/isdk#geoJsonReadObject+JS
I am creating my JSON successfully (I have tested it using the Bing Maps Drag and Drop feature and all of my points show on the map. https://bingmapsv8samples.azurewebsites.net/#GeoJson%20Drag%20and%20Drop.
I am trying to get my GeoJSON to automatically load on a map, and I am receiving a JSON failure, and I am not sure why. (I am rather new to GeoJSON/JSON.)
Javascript:
function loadMapScenario() {
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
credentials: 'KEY',
center: new Microsoft.Maps.Location(32.560116, -117.057889),
zoom: 5
});
Microsoft.Maps.loadModule('Microsoft.Maps.GeoJson', function () {
var featureCollection = Microsoft.Maps.GeoJson.read(getGeoJson(), { polygonOptions: { fillColor: 'rgba(0, 255, 255, 0.3)' } });
for (var i = 0; i < featureCollection.length; i++) {
map.entities.push(featureCollection[i]);
}
});
function getGeoJson() {
$(function (callback) {
var data;
$.ajax({
type: "POST",
url: "/TD/PatGeoJSON",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Hello: " + response.responseText.data)
data = response.RepsonseText;
callback(data)
},
failure: function (response) {
alert("Failure: " + response.responseText);
},
error: function (response) {
alert("Failure: " + response.responseText);
}
});
});
}
}
Controller:
[HttpPost]
public JsonResult PatGeoJSON(string parent)
{
JObject jsondata = JObject.FromObject(new
{
type = "FeatureCollection",
features = from p in pList
select new
{
type = "Feature",
geometry = new Geometry
{
type = "Point",
coordinates = new double?[] { p.GeoLocation.Longitude, p.GeoLocation.Latitude }
},
properties = new Properties
{
MemberName = p.MemberName,
/// etc...
}
}
});
return Json(jsondata, JsonRequestBehavior.AllowGet);
}
My result is currently a "Failure" alert with the JSON string. Note: if I hardcode my GeoJSON as the result from the getGEOJSON function, all of my points show up on the map. Am I not reading the JsonResult correctly in my script?
Your getGeoJson function is asynchronous, so it doesn't return anything, this bing maps is receiving a null value to parse which it simply ignores and this no error. Specify a callback function when loading your geojson and when it responds, then read its value. Here is an updated version of your JavaScript:
function loadMapScenario() {
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
credentials: 'KEY',
center: new Microsoft.Maps.Location(32.560116, -117.057889),
zoom: 5
});
Microsoft.Maps.loadModule('Microsoft.Maps.GeoJson', function () {
getGeoJson(function(data){
var featureCollection = Microsoft.Maps.GeoJson.read(data, { polygonOptions: { fillColor: 'rgba(0, 255, 255, 0.3)' } });
for (var i = 0; i < featureCollection.length; i++) {
map.entities.push(featureCollection[i]);
}
});
});
function getGeoJson(callback) {
var data;
$.ajax({
type: "POST",
url: "/TD/PatGeoJSON",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Hello: " + response.responseText.data)
data = response.RepsonseText;
callback(data)
},
failure: function (response) {
alert("Failure: " + response.responseText);
},
error: function (response) {
alert("Failure: " + response.responseText);
}
});
}
}

Circular reference was detected while serializing an object of type

I am trying to fetch company data based on company id through ajax and fill the related textboxes with the received data. Company id is selected through ajax autocomplete. The code was working fine two days back and suddenly it started generating an error for only first two entries of autocomplete and for rest it is working fine. Can anyone point out the mistake in this. Thank you.
Error Details: "Message":"A circular reference was detected while serializing an object of type \u0027System.Data.Entity.DynamicProxies.Company_81625299B5B4D7A3375D55E48BE84921728B8D48335366DF8CA6844A8D10FF5D\u0027.","StackTrace":" at System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember)\r\n.
Below is my code:
function setCompanyData(pageurl, txtboxid, txtResultid) {
var temp = true;
var searchTbox = $jq14("[id$=" + txtboxid + "]");
var resultTbox = $jq14("[id$=" + txtResultid + "]");
searchTbox.autocomplete({
source: function (request, response) {
$jq14.ajax({
url: pageurl,
data: "{ 'SearchText': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('*')[0],
val: item.split('*')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
autoSelect: true,
autoFocus: true,
select: function (e, i) {
// e.preventDefault();
searchTbox.val(i.item.label);
resultTbox.val(i.item.val).trigger('change');
temp = true;
// return false;
},
change: function (e, i) {
var cId = resultTbox.val();
if (isEmptyOrSpaces(cId)) {
// error
cId = 0;
searchTbox.val("").trigger('');
}
if (isEmptyOrSpaces(searchTbox.val())) {
// error
cId = 0;
resultTbox.val("").trigger('change');
}
getCompanyDetails(cId);
},
minLength: 0
}).focus(function () {
if (temp) {
$jq14(this).autocomplete("search", "");
temp = false;
}
});
searchTbox.autocomplete("widget").addClass("fixedHeight");}
function getCompanyDetails(cid) {
$jq14.ajax({
url: "/sw/adm/update-delete-company.aspx/GetCompanyData",
data: "{ 'cId': '" + cid + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
beforeSend: function () {
$('#loader').show();
},
complete: function () {
$('#loader').hide();
$("#messageBox").hide().slideDown();
setTimeout(function () {
$("#messageBox").fadeOut();
}, 5000);
},
success: function (result) {
$jq14('#cphMainLeft_txtAddress').val(result.d.CompanyAddress);
$jq14('#cphMainLeft_txtCountry').val(result.d.CompanyCountry);
$jq14('#cphMainLeft_txtCity').val(result.d.CompanyCity);
$jq14('#cphMainLeft_txtNewCompanyName').val(result.d.CompanyName);
$jq14('#cphMainLeft_txtEmail').val(result.d.CompanyEmail);
$jq14('#cphMainLeft_txtPanNo').val(result.d.CompanyPAN);
$jq14('#cphMainLeft_txtTinNo').val(result.d.CompanyTIN);
$jq14('#cphMainLeft_txtPhone').val(result.d.CompanyPhone);
$jq14('#cphMainLeft_txtPincode').val(result.d.CompanyPincode);
$jq14('#cphMainLeft_hfTxtCountry').val(result.d.CompanyCountry);
$jq14("#cphMainLeft_ddlCompanyType").val(result.d.CompanyType);
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
}
C# Webmethod goes like:
[WebMethod]
public static Company GetCompanyData(int cId)
{
Entities db = new Entities();
var companyRecord = (from cmp in db.Companies
where cmp.CompanyId == cId
select cmp).SingleOrDefault();
if (companyRecord != null)
return companyRecord;
else
return new Company();
}
Thank you Ashokkumar M. Prajapati for providing the hint.
Instead of returning Company object from [WebMethod], I have converted the company object to Json string in code behind and returned it.
Here is my WebMethod:
[WebMethod]
public static string GetCompanyData(int cId)
{
Entities db = new Entities();
var companyRecord = (from cmp in db.Companies
where cmp.CompanyId == cId
select cmp).SingleOrDefault();
if (companyRecord == null)
companyRecord = new Company();
string s = string.Empty;
s = JsonConvert.SerializeObject(companyRecord,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
return s;
}
Then I updated the success method of getCompanyDetails(cid) to:
success: function (result) {
res = JSON.parse(result.d);
$jq14('#cphMainLeft_txtAddress').val(res['CompanyAddress']);
$jq14('#cphMainLeft_txtCountry').val(res['CompanyCountry']);
$jq14('#cphMainLeft_txtCity').val(res['CompanyCity']);
$jq14('#cphMainLeft_txtNewCompanyName').val(res['CompanyName']);
$jq14('#cphMainLeft_txtEmail').val(res['CompanyEmail']);
$jq14('#cphMainLeft_txtPanNo').val(res['CompanyPAN']);
$jq14('#cphMainLeft_txtTinNo').val(res['CompanyTIN']);
$jq14('#cphMainLeft_txtPhone').val(res['CompanyPhone']);
$jq14('#cphMainLeft_txtPincode').val(res['CompanyPincode']);
$jq14('#cphMainLeft_hfTxtCountry').val(res['CompanyCountry']);
$jq14("#cphMainLeft_ddlCompanyType").val(res['CompanyType']);
}
and it worked wonderfully. Thanks again.

Transforming List into a Json C#

I'm trying to convert a List into a Json to send it to an Ajax Request, but when I recover only one register from the Database it works, but if I have more then one, the ajax returns an error.
Below is my code:
public ActionResult RecuperaLocalidadesPorUsuario(int usuarioId)
{
BpUsuario m = new BpUsuario();
IList<Localidade> states = m.ObterPorId(usuarioId).Localidades.ToList();
states.Add(m.ObterPorId(usuarioId).UsuaAreaPadrao);
var result = (from s in states.Where(x => x != null).Distinct().ToList()
select new { id = s.LocaCodigo, name = s.LocaNome}
).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
Here is the Ajax call
$.ajax({
cache: false,
type: "GET",
url: "#(Url.Action("RecuperaLocalidadesPorUsuario", "Usuario"))",
data: { "usuarioId": selectedItem },
contentType: 'json',
success: function (data) {
alert("entrou no success");
if (data.length == 0) {
ddlLocalidades.find('option').remove();
ddlLocalidades.append($('<option></option>').val("").html("O Usuário não tem localidades cadastradas"));
ddlLocalidades.attr("disabled", true);
} else {
ddlLocalidades.attr("disabled", false);
ddlLocalidades.find('option').remove();
ddlLocalidades.append($('<option></option>').val("").html("Todas"));
$.each(data, function (id, option) {
if (option.id == '#Request.Cookies.Get("UserAreaPadrao").Value') {
ddlLocalidades.append($('<option selected></option>').val(option.name).html(option.name));
} else {
ddlLocalidades.append($('<option></option>').val(option.name).html(option.name));
}
});
}
$('#ddlLocalidades').multiselect('rebuild');
},
error: function (data) {
alert("entrou no error");
}
});
I tried many links here at stackoverflow , but without any success, and I'm really stuck into this problem.

Categories

Resources