Not Showing the output of Json Data from controller to the view - javascript

I am trying to to show the Json data from controller to the view. It works fine in my test project, but when I copied the work in the main project it gives error.
It says Url does not exist in the current context. Although it works fine in the test project and doesn't give this error.
Controller Code -
public JsonResult GetFreight()
{
string url = "https://digitalapi.auspost.com.au/postage/parcel/domestic/calculate.json?length=22&to_postcode=3000&from_postcode=2000&weight=1.5&height=7.7&width=16&service_code=AUS_PARCEL_REGULAR";
//synchronous client.
var client = new WebClient();
client.Headers.Add("auth-key:a1234567-abcd-abcd-1234-1234567890abc");
var content = client.DownloadString(url);
var serializer = new JavaScriptSerializer();
var jsonContent = serializer.Deserialize<Object>(content);
return Json(jsonContent, JsonRequestBehavior.AllowGet);
}
View Code
<script>
var weather = Object();
$(document).ready(function () {
$.get("#Url.Action("GetFreight", "ShoppingCart")", function (response) {
//response
console.log(response);
weather = ko.mapping.fromJS(response); //populate the weather object
ko.applyBindings(weather);
});
});
</script>
<td>Freight = <span data-bind="text:postage_result.total_cost"></span></td>
I want to mention one more thing- In the main project the view is placed in another subfolder called "ShoppingCart" so do I need to change anything in the script when calling the method from the controller? Any help will be appreciated.
Thanks.

Related

How could I pull data from several db tables to automate data entry for user in ASP.NET MVC 5 application?

I have a form in my ASP.NET MVC 5 application that is made up of several different entities that are stored in my database. I am trying to set it up so that, when a user types in the name of a particular entity (let's say a Shipper), the fields in the form that pertain to that entity (e.g. the fields in the Shipper section) are automatically populated with that Shipper's data. Here is what I have tried:
I wrote a class to connect to the database that returns a dataset of Shipper data.
public class DbConnection
{
private string _connectionString = "the connection string";
public DbConnection()
{
}
public DataSet GetShipperData()
{
DataSet shipperData = new DataSet();
try
{
//TODO: replace command with stored procedure name
using(SqlConnection dbConn = new SqlConnection(_connectionString))
{
using (SqlDataAdapter sda = new SqlDataAdapter("select * from dbo.shipper", dbConn))
{
sda.Fill(shipperData);
}
}
return shipperData;
}
catch
{
return null;
}
}
}
}
Here is the method I've written to get the shipper dataset in the controller for the form:
public string[] GetShipperData()
{
DbConnection conn = new DbConnection();
var shipperData = conn.GetShipperData();
List<Shipper> listOfShipperData = shipperData.Tables[0].AsEnumerable().Select(datarow => new Shipper { Name = datarow.Field<string>("Name") }).ToList();
return listOfShipperData;
}
Finally, here is the javascript code in the view where the form is located. I'm using jQuery to call the GetShipperData method in the controller. I have omitted the markup for brevity:
$("#theShipperField").blur(function () {
$.get('#Url.Action("GetShipperData")', function (data) {
var shipperFields = document.getElementsByClassName('form-control shipper');
$(shipperFields).attr("value", data);
});
});
The first error I'm getting is this: In the Shipper fields, I am getting this instead of the data I want: System.Collections.Generic.List1[appname.Models.Shipper]. I think it's because javascript obviously can't work with shipper data, so I need this to be in the form of strings. I'm unsure of how to do this. I would be open to doing this a completely different way, so any help is greatly appreciated. Please let me know if I can provide any additional information.
First: try use Entity Framework
Having your db model in Entity framework I should create web api
[System.Web.Http.Route("api/GetShippers")]
[System.Web.Http.HttpGet]
public IEnumerable<Shipper> GetShippers()
{
var shippers= unitOfWork.GetShippers();
return shippers;
}
After that in your js code
dataservice.js
var dataService = new function () {
getShippers = function (callback) {
$.getJSON(window.applicationBaseUrl + 'api/GetShippers', function (data)
{
callback(data);
});
};
}
index.cshtml
#section scripts{
<script type="text/javascript">
$(document)
.ready(function() {
dataService.getShippers(DoSomething);}
function DoSomething(shippersData) {console.log(shippersData);}
</script>
}

Export CSV using jQuery AJAX call

I have some code to export the results of a search to a CSV file:
$("#exportButton").click(function () {
var url = "/Stuff/ExportSearchResults";
var searchInput = readInput();
$.post(url, searchInput, function (data) {
// This is where I'm clueless.
// I'm getting data back but not sure how to make the
// browser show a prompt to download the file.
console.log(data);
});
});
At the server side (ASP.NET MVC 4) there's this:
[HttpPost]
public FileResult ExportSearchResults(SearchInput model)
{
string csv = GenerateCsv(model);
return File(new UTF8Encoding().GetBytes(csv), "text/csv", "Export.csv");
}
So the good thing is that I'm getting data back in the console. I'm just not sure how I would make the browser show a prompt to download a file.
Here for this question we can go with comment from https://stackoverflow.com/users/5349021/sreepathy-sp
At Client side
$("#exportButton").click(function () {
var url = "/Stuff/ExportSearchResults";
var searchInput = readInput();
window.location.href = '/Stuff/ExportSearchResults?searchInput='+searchInput ;
});
At server side
[HttpGet]
public FileResult ExportSearchResults(string model)
{
string csv = GenerateCsv(model);
Stream stream = new MemoryStream(new UTF8Encoding().GetBytes(csv));
return File(stream , "text/csv", "Export.csv");
}
Hope this will help you out.

Model is null when I'm trying to use it in JavaScript

My app arhitecture is ASP.Net MVC
I'm trying to pass some data from the mssql server using entity framework ORM.
This is the code from my action.
public ActionResult Create()
{
List<object> myModel = new List<object>();
var places = db.Places.Where(p => p.UserId == User.Identity.GetUserId());
myModel.Add(places);
myModel.Add(new Place());
ViewBag.UserId = new SelectList(db.AspNetUsers, "Id", "UserName");
return View(myModel);
}
The code from my view
#model IEnumerable<object>
#{
List<WhereWeDoIt.Models.Place> places = Model.ToList()[0] as List<WhereWeDoIt.Models.Place>;
WhereWeDoIt.Models.Place place = Model.ToList()[1] as WhereWeDoIt.Models.Place;
ViewBag.Title = "Create";
}
...
<script type="text/javascript">
//Users data
var json = #Html.Raw(Json.Encode(places));
console.log("Places test " + json);
</script>
...
The console will output "null"
What am I doing wrong?
Once Html.Raw will get the string and put it directly in the html, try
to put the #Html.Raw between single quotes like:
var json = '#Html.Raw(Json.Encode(places))';
Regards,
The solution that I've provided above will set the json to json string (not object) so will not work, sorry about that. Below there is the solution (simulated and tested in my machine)
Well, we have some things going on here.
I have accomplished success in the code doing so:
#model IEnumerable<object>
#{
var places = Model.ToList()[0];
HypothesisWebMVC.Models.Place place = Model.ToList()[1] as HypothesisWebMVC.Models.Place;
ViewBag.Title = "Create";
}
<script type="text/javascript">
//Users data
var json = #Html.Raw(Json.Encode(places));
console.log("Places test " + json);
</script>
This code will set the json variable to a an object (the places list set in the controller).
I don't know what are your goal but that code that I´ve posted above will work.
Some considerations:
In the actions, when you do:
List<object> myModel = new List<object>();
var places = db.Places.Where(p => p.UserId == User.Identity.GetUserId());
myModel.Add(places);
myModel.Add(new Place());
You're creating an myModel that will have in the first position and list (or IQueryable) of Place, and in the second position a single place (not a list), so you can not convert the whole model to a list.
You could use:
List<WhereWeDoIt.Models.Place> places = Model.ToList()[0] as List<WhereWeDoIt.Models.Place>;
By, when adding to the model, do a .ToList() before inserting.
Consider using a view model (an object created specific for the view)
Hope I've helped.
Regards,
I test your code. Edit view like this:
List<WhereWeDoIt.Models.Place> places = Model.ToList() as List<WhereWeDoIt.Models.Place>;
Model.ToList()[0] is not list.

Data loaded in Angular shows as String instead of Object when getting it from Header var

On an Angular Controller I have the following function:
vm.test = function () {
testService.test()
.then(function (response) {
var pagination = response.data;
var xPagination = response.headers("x-pagination");
console.log(pagination);
console.log(xPagination);
})
}
On the console I see that for pagination is an Object but xPagination shows as:
{ "pageNumber": 2}
So I get undefined when I try:
console.log(xPagination.pageNumber);
But I do not have that problem when using pagination.pageNumber.
The test API I am calling uses ASP.NET API and I have:
On ASP.NET Web Api I have the following:
// This is test code to isolate the problem
public async Task<IHttpActionResult> Test() {
Pagination pagination = new Pagination { PageNumber = 2 };
HttpResponseMessage response = Request.CreateResponse<Pagination>(HttpStatusCode.OK, pagination);
String xPagination = JsonConvert.SerializeObject(pagination, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });
response.Headers.Add("x-pagination", xPagination);
return ResponseMessage(response);
}
What am I missing? I would like xPagination to be an Object in Angular.
Am I doing something wrong in the API or do I need to do something else on Angular part?

Flot.js & JQuery.Ajax: Create graph from key-value-pair

I'm trying to create a graph in mvc using flot.js. The graph will be a line graph with 3 lines on it. I have created a set of 3 list keyvaluepair with date/value to be plotted on the graph as shown in the code below. Currently i get : JavaScript runtime error: 'listvoltage' is undefined
Here's what I tried already:
Index.cshtml:
#if (Model != null)
{
foreach (var item in Model.BatteryInfo)
{
var listvoltage = new List<KeyValuePair<double, int>>();
var listtemperature = new List<KeyValuePair<double, int>>();
var listlevel = new List<KeyValuePair<double, int>>();
listvoltage.Add(new KeyValuePair<double, int>(
TMTMonitorAndCompare_Helpers.DateTimeHelpers.DateTimeToUnixTimestamp(item.TEST_DATE), Convert.ToInt32(item.battery_voltage)));
listtemperature.Add(new KeyValuePair<double, int>(
TMTMonitorAndCompare_Helpers.DateTimeHelpers.DateTimeToUnixTimestamp(item.TEST_DATE), Convert.ToInt32(item.battery_temperature)));
listlevel.Add(new KeyValuePair<double, int>(
TMTMonitorAndCompare_Helpers.DateTimeHelpers.DateTimeToUnixTimestamp(item.TEST_DATE), Convert.ToInt32(item.battery_level)));
CustomGraphinScript.js
$(document).ready(function () {
$.plot($("#placeholder"), listvoltage, { yaxis: { max: 1000 } });
});
Could anyone tell me what I need to do to the above to display this data on graph? is ajax required?
Razor file is executing on the server side. flot.js is executing on client/browser and they dont share the same type system. Thats why 'listvoltage' is undefined.
Put this in your razorfile. Lookout for Date conversion between .NET and Javascript. flot.js need Javascript timestamp.
#using System.Web.Script.Serialization
<script>
#{
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(listvoltage);
}
var timeserie = #Html.Raw(json);
</script>
Consider a Web API solution with JSON result and Ajax call.

Categories

Resources