display json data from controller inside view - c#

Inside my controller there is JsonResult action which returns me a list of House object.
I want onclick using ajax to retrieve these data and to display json data inside my view.
Inside firebug I'm able to see proper Response and Json result but I dont know how to display inside my view.
function GetTabData(xdata) {
$.ajax({
url: ('/Home/GetTabData'),
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ id: xdata }),
success: function (result) {
// tried with these but it doesnt work
// result = jQuery.parseJSON(result);
// alert(result.Title);
},
error: function () { alert("error"); }
});
}
public JsonResult GetTabData()
{
...
var temp = getMyData...
return Json(temp, JsonRequestBehavior.AllowGet);
}
// View page
<div id="showContent">
// Json data should appear here
</div>
Inside firebug JSON tab when success:function(result) is empty
I have following data:
Id 149
PropertyType "Apartment"
StreetNumber "202B"
CityName "Sidney"
Title "My test data"

success: function (json) {
var data = null;
$.each(json.items,function(item,i){
data = '<div>'+item.Id+ ' ' + item.CityName +'</div>';
$("#showContent").append(data);
});
}

First of all, you can specify the dataType attribute in your ajax call to 'json' and then don't have to decode the json response again -
dataType: 'json'
Then, you don't need to use parseJSON. Simply use result.Title etc.
success: function (result) {
alert(result.Title);
var showContent = $('#showContent');
showContent.html(result.Id+','+result.Title);
},

EDIT: As Mukesh said, you can have the ajax function return json without using any extra decoding.
The ajax call result is already an object. You can do whatever you want with it it inside the success function.
For example you could create a table of the information dynamically inside the function, or send the data to another function by calling the function inside that success function. Once you leave the success function, the data is not usable anymore.
Access the data object like any object (data.someProperty).

Related

Json is not properly binded as c# object

My app is made in ASP.NET MVC 5. User can use search form which is displaying filtered data. Now I want to add button which will export displayed data.
To do this I am sending Search object to view and save it in html. Now When clicking export button I want to pass this object to controller, get data from database using this Search object and save results as text.
The thing is I cant bind json to c# object. Thats my view:
<div id="originalForm" style="visibility:hidden">
#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model))
</div>
This is my ajax code:
function exportRaportToCsv() {
var $formData = $('#originalForm').text();
var allIds = getCheckedIds();
var dataToSend = JSON.stringify({
ids: allIds,
search: $formData
});
$.ajax({
type: "POST",
url: '#Url.Action("ExportToCsv", "BankCosts")',
data: dataToSend,
contentType: "application/json; charset=utf-8",
success: function (datar) {
window.location = '/BankCosts/Download?fileGuid=' + response.FileGuid
+ '&filename=' + response.FileName;
},
error: function (xhr) {
},
});
}
And this is my controller:
[HttpPost]
public ActionResult ExportToCsv(string[] ids, Search search)
{
// search is null here
}
When I spy sending data with Fiddler I can see, that I am passing this:
{"ids":[],"search":"\n {\"ID\":0,\"DateFrom\":\"2018-06-23T00:00:00\",\"DateTo\":\"2018-06-25T00:00:00\",\"hasUnrecognizedStatus\":false,\"skippedSearchResults\":0,\"paginationLimit\":100}\n"}
I think it is worth to mention, that ids is properly passed. If it contains data, that data is passed. I think the problem is that I have \ in my json. How can I remove this? Is there something wrong with my ajax?
When I use console.log to print $formData I can see that \ characters are gone and it looks better:
{"ID":0,"DateFrom":"2018-06-23T00:00:00","DateTo":"2018-06-25T00:00:00","hasUnrecognizedStatus":false,"skippedSearchResults":0,"paginationLimit":100}
[HttpPost]
public ActionResult ExportToCsv(string[] ids,[FromBody]Search search)
{
}
Try adding FromBody if your Search model is ok it should work.
based on your comments, I think that search object already stringified, so you don't need to stringify it.
just make your json like this
var dataToSend = {
"ids": allIds,
"search": $formData
};
Use JSON.parse() to transforms JSON string to a JavaScript object. Your $('#originalForm').text() is a JSON string actually.
var $formData = JSON.parse($('#originalForm').text());
var allIds = getCheckedIds();
var dataToSend = JSON.stringify({
ids: allIds,
search: $formData
});
In your case, $formData is a string (JSON string actually). So JSON.stringify() again trying to convert to JSON string which is already a JSON string that's causing unnecessary '/' character in form data that you are posting.
Make sure to set the content type to 'application/json' in ajax call properties Otherwise MVC model binder will not be able to map and fill .NET model from JSON posted data.
contentType: "application/json; charset=utf-8",
Since you are using
JSON.stringify
the search value posted in string format not object
Search
so
Try replace your controller with this
[HttpPost]
public ActionResult ExportToCsv(string[] ids, string search)
{
//then deserialize search json like
Search objSearch = JsonConvert.DeserializeObject<Search>(search);
}
or
[HttpPost]
public ActionResult ExportToCsv(string[] ids, JObject search)
{
//then deserialize search json like
Search objSearch = JsonConvert.DeserializeObject<Search >
(dataModel["search"].ToString());
}
View
$.ajax({
type: "POST",
url: '#Url.Action("ExportToCsv", "BankCosts")',
data:{ids= allIds.toString(),search:JSON.stringify($formData)}
contentType: "application/json; charset=utf-8",
success: function (datar) {
window.location = '/BankCosts/Download?fileGuid=' + response.FileGuid
+ '&filename=' + response.FileName;
},
error: function (xhr) {
},
});

Display data with jQuery autocomplete with WCF Service?

Hi fellow programmers,
I have a database with some data. I Created a WCF Service that uses jQuery Autocomplete to get all names from the database. I get response with JSON but I want to display this in the autocomplete.
This is what my jQuery looks like:
$(function () {
function log(message) {
$("<div>").text(message).prependTo("#log");
$("#log").scrollTop(0);
}
$("#city").autocomplete({
source: function (request, response) {
$.ajax({
url: "/service.svc/GetData",
dataType: "jsonp",
data: {
DataName: request.term
},
success: function (data) {
response(data);
}
});
},
minLength: 3,
select: function (event, ui) {
log(ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
});
I am fairly new to WCF and want to know what the next step is? How do I map the data so I can display it?
The JSON data output looks like this:
{"GetDataResult":[{"Name":"Fran $","CategoryId":102,"dataId":1,"IndexId":16,"InsertedDate":null,"Manual":false}
The autocomplete widget expects the array you supply to the response callback function to be in one of the following formats:
An array of strings, e.g. ["Hello", "Goodbye"]
An array of objects. Each object must have at least either a label property or a value property. It may have other properties as well.
So in your situation you can either:
Edit the server-side code that returns the JSON to conform to the format that the widget expects, or
Modify the results before passing them on to the response callback.
I'll focus on #2. The canonical way to do this is to use $.map to transform the array you got back from the server into the correct format, and then supply the resulting array to the response callback.
In your case that could look something like this:
success: function (data) {
response($.map(data.GetDataResult, function (item) {
return {
label: item.Name,
value: item.dataId
};
}));
}
Example: http://jsfiddle.net/yntrp063/
Note that the value property's value will be used inside of the textbox after you select an item--that might not be what you want.

Posting form data through Ajax is resulting in Null model data

I'm trying to post my form data which is model bound to a controller via an Ajax request however, the controller is showing that the data is null, despite the request header showing the data is being sent.
Code is below. I've tried data: JSON.stringify(form) which results in a null model whereas the below results in a model with null data.
View
$(document).on('click', '#saveData', function () {
if ($('#form').valid()) {
var form = $('#form').serialize();
$.ajax(
{
url: '#Url.Action("CreateClient", "Processors")',
type: 'POST',
cache: false,
async: false,
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(form)
})
.success(function (response)
{ alert(response); })
.error(function (response)
{ alert(response); });
}
});
Controller
public ActionResult CreateClient(ModelData form)
{
if (form == null || !ModelState.IsValid)
{
return Json("Error");
}
return Json("Success");
}
There are two problems with your approach.
If your model class ModelData is, for example,
class ModelData {
public string Foo {get;set;}
public string Bar {get;set;}
}
the appropriate data to send is {foo:"foo1", bar:"bar1"}, or eventually {Foo:"foo1", Bar: "bar1"}, depending on how you have configured your serialization - as you have specified contentType 'application/json'.
However, you are reading your form using jquery serialize(). This method returns a string, on the form "foo=foo1&bar=bar1", appropriate for contentType 'application/x-www-form-urlencoded'. So you have to make up your mind on in what format you want to send the data. If you want to continue to use serialize() to obtain the data from the DOM, use 'application/x-www-form-urlencoded' instead.
Secondly, JSON.stringify() will create a JSON string from an object. A string is an object, too. So passing a string to this function will wrap the string in a string, which doesn't make much sense: The data will be something like "\"foo=foo1&bar=bar1\"". In the same manner, the jQuery ajax function will expect an object for it's data parameter when contentType is 'json', so if you convert your object to a string before, it will be sent just as that: a string. Basically, whatever contentType you end up choosing for your request, don't use JSON.stringify for your data parameter.
TL;DR: To get this working, use the default contentType or declare it explicitly as per below, and pass the form variable as-is:
var form = $('#form').serialize();
$.ajax(
{
//(...)
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: form,
//(...)

Server result to webpage

I am trying to simply write out some data to my webpage as a result of a callback. Everything works up until the point where I need to output the result of the callback.
Client-side:
function toServer(data) {
var dataPackage = data + "~";
jQuery('form').each(function () {
document.getElementById('payload').value = JSON.stringify({ sendData: dataPackage });
$.ajax({
type: "POST",
async: true,
url: window.location.href.toString(),
data: jQuery(this).serialize(),
success: function (result) {
//this does not work because it just puts an entire source code copy of my site in there instead...
//document.getElementById('searchResults').value = result
console.log("callback compelete");
},
error: function(error) {
console.log("callback Error");
}
});
});
}
Server-Side: (on page load)
//holds actions from page
string payload = HttpContext.Current.Request.Form["payload"] ?? String.Empty;
// See if there were hidden requests (callbacks)
if (!String.IsNullOrEmpty(payload))
{
string temp_AggregationId = CurrentMode.Aggregation;
string[] temp_AggregationList = temp_AggregationId.Split(' ');
Perform_Aggregation_Search(temp_AggregationList, true, Tracer);
}
else
{
HttpContext.Current.Session["SearchResultsJSON"] = "";
}
The rest of the server-side code works properly and just handles the parsing of the incoming and performs a search of the db and then parses the search results into a JSON obj.
Currently, the only way the json obj gets written to the page is if I call it without the callback (just call it on page load). Also, in firebug, it looks like the entire page source is posting back as the 'result' of the callback. I do see my json result within the posted back 'result' but it also contains the entire page HTML.
Moreover, I can't seem to get the result to post to the page which is the whole point. Actually, I could get the result to post to the page by simply uncommenting that bit in the client side code but it posts a copy of my site and not the actual result I thought I created...
What am I missing? How do you explicitly state in the C# code what is returned to the JS callback as 'result'?
You get the entire page because you're making a request to an ASP.NET page. In fact, you're requesting the vary same page you're viewing. The server is returning what it would return if you were submitting a form.
To get JSON data, you need to create a web method to handle your request. Read this article, it will help you. It shows you how to return simple text, but you can return JSON too. Information on this MSDN article.
Finally, to make sure jQuery is parsing the server response as JSON, change your request and indicate it explicitly:
function toServer(data) {
var dataPackage = data + "~";
jQuery('form').each(function () {
document.getElementById('payload').value = JSON.stringify({ sendData: dataPackage });
$.ajax({
type: "POST",
async: true,
url: window.location.href.toString(),
data: jQuery(this).serialize(),
dataType: 'json',
success: function (result) {
//this does not work because it just puts an entire source code copy of my site in there instead...
//document.getElementById('searchResults').value = result
console.log("callback compelete");
},
error: function(error) {
console.log("callback Error");
}
});
});
}

Fill jQuery Variable from serverside on load

I was looking on internet for over 2 hrs now, trying to find simple example of how to fill jQuery Variable from serverside code on load of asp.net page.
What i have so far:
I have a button which call this jquery code:
function GetListOfQuestions() {
$.ajax({
type: "POST",
url: 'UserProfile.aspx/getQuestions',
contentType: "application/json; charset=utf-8",
dataType: "json",
error: OnAjaxError,
success: AjaxSucceeded
});
//$.getJSON('UserProfile.aspx/getQuestions', {}, function (data) {
// alert(data);
//});
}
function AjaxSucceeded(result) {
alert(result);
}
GetListOfQuestions calls serverside :
[WebMethod]
public static List<Question> getQuestions(){
var userGuid = (Guid)System.Web.Security.Membership.GetUser().ProviderUserKey;
IEnumerable<Question> list = Question.getQuestionsForUser(userGuid).Select(x => new Question
{
Uid = x.Uid,
Content = x.Content
});
return list.ToList();
}
result return an object if I alert it, so it must contain some kind of data, but I can't find any example of how I can retrieve data again on client side.
I'm not sure if what I am doing right now is right at all (I'm new to jQuery). So how can I retrieve data from result variable again?
There could be better ways but this is one way I know of:
[WebMethod]
public static string getQuestions(){
var userGuid = (Guid)System.Web.Security.Membership.GetUser().ProviderUserKey;
IEnumerable<Question> list = Question.getQuestionsForUser(userGuid).Select(x => new Question
{
Uid = x.Uid,
Content = x.Content
});
return new JavaScriptSerializer().Serialize(list.ToList())
}
In your jQuery method, you can
result = $.parseJSON(data) ;
Do a console.log(result) to see how to iterate through result, should be just a for loop.
Put a hidden field on your page an set the variable value there, later read the hidden value from js.
Another option is to use ScriptManager.RegisterStart UpScript to write your variable directly as js to the page.

Categories