I have a controller action like this:
List<string> abcd = new List<string>()
foreach (var i in images)
{
abcd.Add("{url:'"+GetImageUrl(i)+"'}");
}
return Json(abcd, JsonRequestBehavior.AllowGet);
So the output of abcd is
["{url:'/PropertyImage/GetPropertyImage?imageId=1'}", "{url:'/PropertyImage/GetPropertyImage?imageId=2'}", "{url:'/PropertyImage/GetPropertyImage?imageId=8'}"]
But the result I want is:
images:[{url:'/PropertyImage/GetPropertyImage?imageId=1'}, {url:'/PropertyImage/GetPropertyImage?imageId=2'}, {url:'/PropertyImage/GetPropertyImage?imageId=8'}]
In my JavaScript, I have
$.ajax({
type: "GET",
url: url,
success: function (result) {
console.log(JSON.stringify(result));
var data = {
images: [result]
};
template = "{{#images}}<a href='{{url}}'><img class='imageborder' src='{{url}}' style='width:150px;height:150px'></img></a>{{/images}}";
renderedOutput= Mustache.to_html(template,data);
$('#Propertyimagelinks').html(renderedOutput);
}
});
How can I get the correct output?
Rather than trying to manually manipulate JSON strings, it seems a lot simpler to use ASP.NET MVC's built in JSON serialization functionality and a little bit of Linq, like this:
var abcd = images.Select(i => new { url = GetImageUrl(i) }).ToList();
return Json(abcd, JsonRequestBehavior.AllowGet);
And in your JavaScript result handler, use this:
var data = { images: result };
Alternatively you can use this in your controller:
var abcd = images.Select(i => new { url = GetImageUrl(i) }).ToList();
return Json(new { images = abcd }, JsonRequestBehavior.AllowGet);
And in your JavaScript:
var data = result;
Related
I can't display the date in the list in json format. How should I follow a path. My angular js knowledge is not good but I need to use it.
HtmlPage
<tbody ng-init="GetAllMatches()">
<tr ng-repeat="m in filteredlist =(matches.data
| filter:filterlist)
| orderBy:sort:reverse
| pagination: currentPage : numPerPage"
ng-if="gamePlayed">
<td>{{m.HomeTeamName}}</td>
<td>{{m.AwayTeamName}}</td>
<td>{{m.StadiumName}}</td>
<td>{{m.Referee}}</td>
<td>{{m.Weather}}</td>
<td>{{ m.StartDate}}</td>
</tr>
</tbody>
.netMVC
var matches = await AppService.MatchService.GetMatchesAsync();
return Json(new { data = matches }, JsonRequestBehavior.AllowGet);
JS
$scope.GetAllMatches = function () {
$http({
method: "GET",
url: "/Match/GetAllMatchAsync"
}).then(function (response) {
$scope.matches = response.data;
}, function () {
alert("error");
});
};
View
/Date(1537909200000)/
Solved
I haven't found any information on your problem, but...
As a solution:
{{m.StartDate.slice(6, -2) | date: 'yyyy-MM-dd HH:mm:ss' }}
Why is your API not returning dates in ISO 8601 format? If you return strings in ISO 8601 format then you just wrap your field function like this
function parseISO8601Date(dateStr) {
return new Date(dateStr);
}
If you really can't change API to return proper ISO 8601 formatted date strings then maybe this blog entry will help you https://weblog.west-wind.com/posts/2014/Jan/06/JavaScript-JSON-Date-Parsing-and-real-Dates
Here is if link dies
if (window.JSON && !window.JSON.dateParser) {
var reISO = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*))(?:Z|(\+|-)([\d|:]*))?$/;
var reMsAjax = /^\/Date\((d|-|.*)\)[\/|\\]$/;
JSON.dateParser = function (key, value) {
if (typeof value === 'string') {
var a = reISO.exec(value);
if (a)
return new Date(value);
a = reMsAjax.exec(value);
if (a) {
var b = a[1].split(/[-+,.]/);
return new Date(b[0] ? +b[0] : 0 - +b[1]);
}
}
return value;
};
}
var date = JSON.parse(json,JSON.dateParser);
console.log(date);
I am working on MVC 5 project.
string hdPrimUserFirstReg = "{\"ProjectName\":\"wwwwwww\",\"ClientName\":\"asdw\",\"ProjectType\":\"2\",\"ProjectLocation\":\"asdfasdfs\",\"Status\":\"Completed\"},\"Form6\":null}","hdPremUserProject":"","hdclientLogo":"","hdProjectTitle":"","ProjectName":"eeeeeee","ClientName":"asdwedfswe","ProjectType":"1","ProjectLocation":"dfwea","Status":"Completed}";
I want to create a list of ProjectName from the variable hdPrimUserFirstReg JSON format data and also from the Form 5 into the public IList<string> listProjectName { get; set; }
And this is my java-script,
AddProjectList: function (e) {
debugger;
if (this.validateForm()) {
debugger;
var hidvalue = $('#hdPrimUserFirstReg').val();//// hidden field from same form
var hidJson = JSON.parse(hidvalue);
var json = {};
$.each($('#frmSubmitPremUserRegFirst').serializeArray(), function (i, field) {
json[field.name] = field.value || '';
});
hidJson.Form5 = json;
var str = JSON.stringify(hidJson);
$('#hdPrimUserFirstReg').val(str); // hidden field from same form
}
},
Error: cannot deserialize the current json object (e.g. {“name”:“value”}) into type 'system.collections.generic.list`1
How can I do this ?
Please help me...
var hdPrimUserFirstRegList =
JsonConvert
.DeserializeObject<List<hdPrimUserFirstRegModel>>(pageVM.hdPrimUserFirstReg );
var projectsNames = hdPrimUserFirstRegList.Select(x=>x.ProjectName).toList();
And create model hdPrimUserFirstRegModelcontains all json object properties.
Try this
var listProjectName = JsonConvert .DeserializeObject<List<hdPrimUserFirstRegModel>>(pageVM.hdPrimUserFirstReg ).Select(x => x.ProjectName).ToList()
I'm trying to code a simple autocomplete using LINQ to entities and Razor (new to c# sharp as well) and i'm having trouble displaying json data in my view.
My controller is as follows:
public ActionResult AutoCompleteCity(string guess)
{
List<City> listData = null;
if (!string.IsNullOrEmpty(guess))
{
listData = db.AutoCompleteCity(guess);
}
return Json(new { Data = listData });
}
AJAX call:
function getCities(input) {
var serviceURL = $("#autocompleteURL").val();
var url =
$.ajax({
type: "POST",
url: serviceURL,
data: {
'guess': input
},
dataType: 'json',
success: function (response) {
if (response.Data != null) {
if ($("#targetUL") != undefined) {
$("#targetUL").remove();
}
Data = response.Data;
$.each(Data, function (i, value) {
$("#targetUL").append($("<li class='targetLI' onclick='javascript:agregarTexto(this)'>" + JSON.stringify(value) + "</li>"));
});
});
}
I might be missing a bracket or two :D
Any way when i retrieve records from the database and try to pass JSON values to the view the output is:
{"Data":[{"Selected":false,"Text":null,"Value":null}]}
I assume I'm not passing the JSON listData correctly. Any input will be greatly appreciated, thanks!
EDIT: here is a screencap of the values returned by listData in my controller
This is my LINQ query
public List<City> AutoCompleteCity(string guess)
{
using (var context = new Sports.SportsEntities())
{
var query = (from loc in context.city
join prov in context.state on loc.STATE_ID equals prov.STATE_ID
where loc.CITY_DESC.Contains(guess.ToUpper())
select new
{
city = loc.CITY_DESC,
state = prov.STATE_DESC,
});
IEnumerable<City> cityList= from ba in query.AsEnumerable()
select new City(ba.city, ba.state);
return cityList.ToList();
}
}
This error:
{"Data":[{"Selected":false,"Text":null,"Value":null}]}
was caused by having declared private attributes in the City Class, or by failing to declare getter/setter methods if said attributes are meant to be private.
I figured that out by looking at the screen capture posted on my question, only displaying the "selected", "text" and "value" properties and not the city and state description in the query results, which was what I needed to display below the textbox input.
This controller method will do the trick:
public JsonResult AutoCompleteCity(string term)
{
List<City> listData = new List<City>();
if (!string.IsNullOrEmpty(term))
{
listData = db.AutoCompleteCity(term);
}
return Json(listData, JsonRequestBehavior.AllowGet);
}
The problem is probably this piece of code in the AJAX call:
if ($("#targetUL") != undefined) {
$("#targetUL").remove();
}
By doing this you are removing the ul tag from the DOM and therefore cannot add the li elements you are constructing in this piece of code:
$.each(Data, function (i, value) {
$("#targetUL").append($("<li class='targetLI' onclick='javascript:agregarTexto(this)'>" + JSON.stringify(value) + "</li>"));
});
If you want to clear the list use .empty():
if ($("#targetUL") != undefined) {
$("#targetUL").empty();
}
if you want to return a JSON, change that:
public ActionResult AutoCompleteCity(string guess)
by
public JsonResult AutoCompleteCity(string guess)
and also try that:
Data = JSON.parse(response.Data);
It looks like your method returns a list of City objects, so maybe you need to use the property of that objects to get to the city name, something like this:
$.each(Data, function (i, city) {
$("#targetUL").append($("<li class='targetLI' onclick='javascript:agregarTexto(this)'>" + city.Name + "</li>"));
});
I have created one string array in jquery of name array[] and pushed values to it.
How can I send this array in query string?
For example window.location.href('ViewData?array');
And how can I get back the array data from query string in jquery itself ?
Please advice?
This is very easy to achieve with jQuery as it has a helper function called param().
var myData = {
name: "John Doe",
age: 23,
children: [{
name: "Jane Doe",
age: 13,
children: []
},
{
name: "John Doe Jr.",
age: 16,
children: []
}
],
}
var p = $.param(myData)
The results:
"name=John+Doe&age=23&children%5B0%5D%5Bname%5D=Jane+Doe&children%5B0%5D%5Bage%5D=13&children%5B1%5D%5Bname%5D=John+Doe+Jr.&children%5B1%5D%5Bage%5D=16"
You can use it like so:
window.location = "/MyController/MyAction?" + p;
As for getting parameters from query strings, please refer to the following question: How can I get query string values in JavaScript?
Another thing you can do is use an ajax call, this way you don't have to serialize the data yourself as it is done for you automatically.
$.ajax({
url: "/MyController/MyAction",
data: myData,
dataType: "json",
type: "POST",
success: function(data){
//'data' is your response data from the Action in form of a javascript object
}
})
I think this is what you are looking for. Let me know if I get it wrong. I copied $.parseParams from this link. You can also see working code here
(function($) {
var re = /([^&=]+)=?([^&]*)/g;
var decodeRE = /\+/g; // Regex for replacing addition symbol with a space
var decode = function (str) {return decodeURIComponent( str.replace(decodeRE, " ") );};
$.parseParams = function(query) {
var params = {}, e;
while ( e = re.exec(query) ) {
var k = decode( e[1] ), v = decode( e[2] );
if (k.substring(k.length - 2) === '[]') {
k = k.substring(0, k.length - 2);
(params[k] || (params[k] = [])).push(v);
}
else params[k] = v;
}
return params;
};
})(jQuery);
var s=["abc", "xyz", "123"];
var queryString=$.param({a:s});
console.log("object to query string: ", queryString);
console.log("query string to object: ", $.parseParams(queryString));
Hi i have a table with following values
Country Count
China 2
India 3
Pakistan 3
i want these in JSON as "China" : 2,"India" : 3,"Pakistan" : 3
I don't want the header Count and Country. I Have tried using ajax and HTTP Handler but no avail
$(document).ready(function () {
$.ajax({
url: 'CountryRegistrations.ashx',
type: 'POST',
dataType: 'json',
success: function (data) {
var test = data.Country + data.Count;
alert(test);
},
error: function (data) {
alert("Error");
}
});
});
public void ProcessRequest(HttpContext context)
{
FilterCountry emp = getCounts();
// serialize and send..
JavaScriptSerializer serializer = new JavaScriptSerializer();
StringBuilder sbJsonResults = new StringBuilder();
serializer.Serialize(emp, sbJsonResults);
context.Response.Clear();
context.Response.ContentType = "application/json; charset=utf-8";
context.Response.Write(sbJsonResults.ToString());
}
private FilterCountry getCounts()
{
FilterCountry fc = new FilterCountry();
fc.Country = "PK";
fc.Count = 600;
return fc;
}
I gives me as PK600 but it should give "PK":600 and how to get these values from database right now im trying to get from hard coded values.
var test = data.Country + data.Count;
Try to change to:
var test = data.Country + ':' + data.Count;
If you are using JavaScriptSerializer then it will will serialize the object in to JSon format like "Key":"Value" that is also based on the object you are passing to Serialize method.
Your class "FilterCountry" has two property "Country" and "Count" and assigning values on it.
So it will be serialize like as follows { "Country" : "PK", "Count":600 }
Please go through JSon and serialize examples