I am using openweather api to get weather data.when i enter the city name the server returns a json data I need to know how to handle the data and i need to display the data inside a div
function loadweather() {
var q = document.getElementById("in").value;
var appid = document.getElementById("appid").value;
var url = 'http://api.openweathermap.org/data/2.5/weather?q=' + q + '&appid=' + appid;
$.getJSON(url, function(data) {
console.log(data)
});
}
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<input type="text" id="in" value="New Delhi"/>
<input type="hidden" id="appid" value="086a3e2bd775aac95a9b096b5233f049">
<button id="go" onclick="loadweather()">Search</button>
<div id="disp"></div>
You can access the data You got as an object. In your case the object will be as shown below.
public class RootObject
{
public Coord coord { get; set; }
public List<Weather> weather { get; set; }
public string #base { get; set; }
public Main main { get; set; }
public int visibility { get; set; }
public Wind wind { get; set; }
public Clouds clouds { get; set; }
public int dt { get; set; }
public Sys sys { get; set; }
public int id { get; set; }
public string name { get; set; }
public int cod { get; set; }
}
You can access it script itself as shown below.
$.getJSON(url, function (data) {
$('#disp').html('Temperature:' + data.main.temp + 'deg Fahrenheit' + 'Pressure:'+ data.main.pressure)
});
Related
I have several input fields on my page. Now on button click event, I want to call a WCF service which is responsible for storing data into the database.
<asp:Button runat="server" ID="btnCreateApplyTemplate" Text="Create" Style="text-transform: uppercase; color: #fff;"
CssClass="btn lr-small-btn-template lr-btn-success" ClientIDMode="Static" OnClientClick="return SaveMockTestData(this);" />
page.ascx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ScriptManager manager = ScriptManager.GetCurrent(Page);
ServiceReference srMockTest = new ServiceReference("~/WCFSERVICES/MockTest.svc");
manager.Services.Add(srMockTest);
ScriptReference dd1 = new ScriptReference("~/SvcToDb/JsMocktest.js");
manager.Scripts.Add(dd1);
}
}
Now let me show you what is inside the file, JsMocktest.js
(function (global, undefined) {
var mocktest = {};
var mockTestData = {};
function SaveMockTestData(args) {
if (args.value == "Save Template") {
mockTestData.TemplateName = mocktest.txtTemplateName.value;
mockTestData.TotalMarks = mocktest.txtTotalMarks.value;
mockTestData.ExamDuration = mocktest.txtDuration.value;
mockTestData.TotalQuestion = mocktest.txtTotQuestion.value;
//question types
let chkisMcq = mocktest.chkisMcq.checked;
let txtMcqTypePostvMark = mocktest.txtMcqTypePostvMark.value;
let txtMcqTypeNegtvMark = mocktest.txtMcqTypeNegtvMark.value;
let chkisNonMcq = mocktest.chkisNonMcq.checked;
let txtNonMcqTypePostvMark = mocktest.txtNonMcqTypePostvMark.value;
let txtNonMcqTypeNegtvMark = mocktest.txtNonMcqTypeNegtvMark.value;
var questionTypes = {
qtype: []
};
if (chkisMcq) {
questionTypes.qtype.push({
"isMcq": true,
"PostiveMarks": txtMcqTypePostvMark,
"NegetiveMark": txtMcqTypeNegtvMark,
});
}
if (chkisNonMcq) {
questionTypes.qtype.push({
"isMcq": false,
"PostiveMarks": txtNonMcqTypePostvMark,
"NegetiveMark": txtNonMcqTypeNegtvMark,
});
}
debugger;
mockTestData.TotalQuestionType = questionTypes;
var table = $('#tableContainer').tableToJSON({
ignoreColumns: [3]
}
);
mockTestData.TotalSections = table;
mockTestData.CalculatorTupe = mocktest.ddlCalcType.value;
mockTestData.IsAutoSave = mocktest.chkIsAutoSave.checked;
mockTestData.IsQuizPause = mocktest.chkCanPause.checked;
mockTestData.IsMultilingualSupport = mocktest.chkIsMultLingual.checked;
mockTestData.ExamInstruction = mocktest.chkExamInstruction.checked;
mockTestData.ExamInstructionId = mocktest.ddlExamInstruction.value;
var IMockTetst = new WcfAjaxServices.IMockTest();
debugger;
IMockTetst.InsertTemplateData(mockTestData, function (result, context, OnSuccess) {
}, function (error, context, OnError) {
//toastify("error", "ppp", "System Error", "toast-bottom-right", true);
}, null);
}
return false;
}
global.$MockTestControlID = mocktest;
global.SaveMockTestData = SaveMockTestData;
})(window);
Now here is the Service,
public class MockTest:IMockTest
{
readonly BO_MockTest _objBoMockTest = new BO_MockTest();
BL_MockTest objBL_BusinessPartners = new BL_MockTest();
public int InsertTemplateData(TemplateData data)
{
_objBoMockTest.Flag = "1";
_objBoMockTest.TemplateName = data.TemplateName;
_objBoMockTest.TotalMarks = data.TotalMarks;
_objBoMockTest.ExamDuration = data.ExamDuration;
_objBoMockTest.TotalQuestions = data.TotalQuestion;
//_objBoMockTest.TotalQuestionTypes = data.TotalQuestionType;
//_objBoMockTest.TotalSections = data.TotalSections;
_objBoMockTest.CalculatorType = data.CalculatorTupe;
_objBoMockTest.IsAutoSave = data.IsAutoSave;
_objBoMockTest.IsQuizPause = data.IsQuizPause;
_objBoMockTest.IsMultilingualSupport = data.IsMultilingualSupport;
_objBoMockTest.IsContainExamInstruction = data.ExamInstruction;
_objBoMockTest.ExamInstructionId = data.ExamInstructionId;
return 0;
}
}
here is the interface,
[ServiceContract(Namespace = "WcfAjaxServices")]
public interface IMockTest
{
[OperationContract]
int InsertTemplateData(TemplateData data);
}
[DataContract]
public class TemplateData
{
[DataMember]
public string TemplateName { get; set; }
[DataMember]
public string TotalMarks { get; set; }
[DataMember]
public string ExamDuration { get; set; }
[DataMember]
public string TotalQuestion { get; set; }
[DataMember]
public string TotalQuestionType { get; set; }
[DataMember]
public string TotalSections { get; set; }
[DataMember]
public string CalculatorTupe { get; set; }
[DataMember]
public bool IsAutoSave { get; set; }
[DataMember]
public bool IsQuizPause { get; set; }
[DataMember]
public bool IsMultilingualSupport { get; set; }
[DataMember]
public bool ExamInstruction { get; set; }
[DataMember]
public string ExamInstructionId { get; set; }
}
Now I dont have any clue how to map my json object i.e mockTestData with TemplateData and more overover
how to call int InsertTemplateData(TemplateData data); this method from my javascript code..
Edit In My Post
I just changed my WCF method like this,
[OperationContract]
int InsertTemplateData();
instead of using
[OperationContract]
int InsertTemplateData(TemplateData data);
and
public class MockTest:IMockTest
{
readonly BO_MockTest _objBoMockTest = new BO_MockTest();
BL_MockTest objBL_BusinessPartners = new BL_MockTest();
public int InsertTemplateData()
{
TemplateData data = new TemplateData();
_objBoMockTest.Flag = "1";
_objBoMockTest.TemplateName = data.TemplateName;
_objBoMockTest.TotalMarks = data.TotalMarks;
_objBoMockTest.ExamDuration = data.ExamDuration;
_objBoMockTest.TotalQuestions = data.TotalQuestion;
//_objBoMockTest.TotalQuestionTypes = data.TotalQuestionType;
//_objBoMockTest.TotalSections = data.TotalSections;
_objBoMockTest.CalculatorType = data.CalculatorTupe;
_objBoMockTest.IsAutoSave = data.IsAutoSave;
_objBoMockTest.IsQuizPause = data.IsQuizPause;
_objBoMockTest.IsMultilingualSupport = data.IsMultilingualSupport;
_objBoMockTest.IsContainExamInstruction = data.ExamInstruction;
_objBoMockTest.ExamInstructionId = data.ExamInstructionId;
return 12;
}
}
and called like this,
IMockTetst.InsertTemplateData(function (result, context, OnSuccess) {
debugger;
}, function (error, context, OnError) {
//toastify("error", "ppp", "System Error", "toast-bottom-right", true);
}, null);
and doing so I am getting, the result as expected. So it means there is a problem with mockTestData which I am passing from javascript and the TemplateData which is receiving it...
My question is how to map those two variables? I think there is an issue with mapping .. ?? Help needed please :)
It seems that you have resolved the issue that how to call WCF service from the Javascript code. The rest problem is how can we pass the parameter to method when using a JSON object.
Please refer to the example.
<script>
function Calculate() {
var product = { "Name": "apple", "Amount": 3, "Price": 4.23 };
CostService.CostOfProducts(product, function (result) {
console.log(result)
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/Content/CostService.svc" />
</Services>
</asp:ScriptManager>
<div>
Calculate the total prices of the Products.
</div>
<input type="button" value="Price of 3 sandwiches" onclick="Calculate()" />
<br />
<span id="additionResult"></span>
</form>
</body>
SVC file.
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class CostService
{
[OperationContract]
public double CostOfProducts(Product product)
{
return product.Amount * product.Price;
}
}
[DataContract]
public class Product
{
[DataMember]
public string Name { get; set; }
[DataMember]
public int Amount { get; set; }
[DataMember]
public double Price { get; set; }
}
Feel free to let me know if there is anything I can help with.
I have a object that I am trying to pass to my C# controller. All the properties get populated except the list I have is always count =0. I have tried setting the header to content-type/json and Json.stringify. Also for testing I am returning the product list from another call so I know that returns a list of products to my view that is formatted correctly.
example for creating request
var request =
'Id':null,
...
... rest of data is here standard properites
...
'Products':productlist
for product list I am currently using the return value from a call that returns a List
return $http.post('api/Enty/Save', request )
.error(function (data, status, headers, config) {
errorLog('error: ' + data);
});
public class Person:IPerson
{
[Required]
public int Id { get; set; }
[MaxLength(90)]
public String Address1 { get; set; }
[MaxLength(90)]
public String Address2 { get; set; }
[MaxLength(40)]
public String Address3 { get; set; }
[MaxLength(40)]
public String City { get; set; }
[MaxLength(2)]
public String State { get; set; }
[MaxLength(40)]
public String Province { get; set; }
[MaxLength(10)]
public String Zip { get; set; }
public IList<IProduct> Products { get; set; }
}
[HttpPost()]
public Response Save(person r)
{}
UPDATE
If I make it List instead of IList it works. Any ideas why?
Turns out the issue was not the Ilist but the Iproduct. I just changed to a concrete class for that property
I am working on displaying data in a separate div and when I pass my javascript function data it does not fire onclick. It works when I use data from the parent but not after I cast the data from the parent into a child and try to pass the JS function with that data.
##view##
#using WebApplication2.Models
#model IEnumerable<WebApplication2.Models.OBJECT>
#{
ViewBag.Title = "CompAndMon";
}
<script>
//this function does not fire when called
function setO(OfficeLocation,Name,Email,Phone,NumComputers,NumMonitors) {
var text = "Primary Contact Name " + Name+"\n Primary Contact Email: " +Email +"\n Primary Contact Phone: " +Phone +"\n Number of Computers: " +NumComputers +"\n Number Of Monitors: " +NumMonitors;
var location = "Office Location: " + OfficeLocation;
document.getElementById("Nametag").innerHTML = location;
return document.getElementById("OCM").innerHTML = text;
}
//this function does not fire when called
function setComputer(lastS) {
var text = "you selected Item No: " + lastS;
return document.getElementById("OCM").innerHTML = text;
}
//this function operates correctly
function setMonitor(id) {
var text = "you selected Item No: " + id;
return document.getElementById("OCM").innerHTML = text;
}
</script>
#foreach (var item in Model)
{
if (#item.Type == 1)
{
var office = item as Office;
var loc = #office.OfficeLocation;
var Name = #office.Name;
var email = #office.Email;
var phone = #office.Phone;
var mons = #office.NumMonitors;
var comps = #office.NumComputers;
<p><a onlick="setO(#loc,#Name,#email,#phone,#comps,#mons)">#office.Name</a></p>
}
else if (#item.Type == 2)
{
var computer = item as Computer;
<p> <a onclick="setComputer(#computer.LastUser)">#item.Name1</a></p>
}
else
{
var monitor = item as Monitor;
<p> <a onclick="setMonitor(#item.ID)">#item.Name1</a></p>
}
}
<h2 id="Nametag" style="text-align:center"></h2>
<div id ="OCM"class="row">
Select a computer or monitor and the information about the de will be displayed here.
</div>
and here are the class models that the view uses
##OCM.cs##
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace WebApplication2.Models
{
public abstract class OBJECT
{
public int ID { get; set; }
public int Type { get; set; }
public string Name1 { get; set; }
}
public class Office:OBJECT
{
public string OfficeLocation { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public int NumComputers { get; set; }
public int NumMonitors { get; set; }
}
public class Computer:OBJECT
{
public String LastUser { get; set; }
public String Name { get; set; }
public int NumMonitors { get; set; }
public String TotalHDSpace { get; set; }
public String FreeHDSpace { get; set; }
public int NumUpdates { get; set; }
}
public class Monitor:OBJECT
{
public String Manufacturer { get; set; }
public String ModelID { get; set; }
public String SerialNum { get; set; }
public int HoursON { get; set; }
public String LastTestTime { get; set; }
public String LastTestType { get; set; }
}
}
When I inspect the element chrome it shows that the data is being passed the the function, but it doesn't run so I am not sure what to do. any help would be appreciated
Here shows that the data was passed to the JS functions when I inspect the element
You use string without quote
setComputer('ted') or setComputer(\"ted\") and not setComputer(ted)
this is the same for email and other arguments
I found that I misspelt onclick in the setO() call and needed to pass my razor variables to the javascript function in single quotes.
I have a Web API that is returning some info along with a image (byte array)
var result = response.Result.Content.ReadAsStringAsync();
Snippet:
{"CompanyName":"MyCompany","Address":"Address1","Logo":"iVBORw0KGgoAAAANSUhEUgAAAKAAAABQCAYAAACeXX40AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAW6gAAFuoB5Y5DEAAAABx0RVh0U29mdHdhcmUAQWRvYmUgRmlyZXdvcmtzIENTNui8sowAAAAWdEVYdENyZWF0aW9uIFRpbWUAMDcvMjUvMTZmHO7IAAAB6HByVld4nO2WYVKDMBCFowkl3MIreBOv4A/xb6/DZTyAw128gUjFNsmyCRuglDrvSwdtl83blw1MPr8/vtRRHbuua9v+0zZN1zT9taeu67auT38UAAAAAAAAAAAAAABgIbbaaET0t5Kv4H+X/vvITf27Oyz5d8Xvaf9sCZcf1vq+0/5vJX9f/q3RJwz/bBTlb9iUEaliSC4Pcv/uchqD+lABU5yLliTi1U7Lj+tTAR1CouVjEKXZVo/CEv/eMOEMugjWpiRRWh4NZ/efTuDP0X8extG4ez9Z6p/RT1c3ET7vIKF/TkAn5XW6Op3WD+ULXt8kqyvSxRfT6z/hwD2FfHgiO8M/78Ap8NGJ7Jz+R/QX+c/Z/zv1/xe9Qv/J65e+/AbS+9+k/RvJ+qensEmDsmRJ/y37BvUecFahSodtTv/tIT5DrD8T26fK2f+cB+OHx8Wlsy8nBKH/8+lFLECyo4sj9e8fYDR3ADLs9Pwm9NJS+lRDfP4anfaDAs1dnf/ZlVhv7N7/lUe+f3e5on+JhLtHUlLknin/c91K88T9l003lh3nBfdg/8/3Hyzkuv7zpl5Qhtz/Urd8/oz+x8vwJYTlbr3/aVkRfQAAAAAAAAAAAAAAAAAA/C9e1Kt6V2/qST3fuhRwA34ABnmlFTLkCiwAAABIbWtCRvreyv4AAAAEAAAAAAAAAAAAAAAAA="}
So when I try to map
var profile = new JavaScriptSerializer().Deserialize<WebApi.Common.DomainObjects.WebProfile>(result);
public class WebProfile
{
public string CompanyName { get; set; }
public string Address { get; set; }
public byte[] Logo { get; set; }
}
I get this error:
Cannot convert object of type 'System.String' to type 'System.Byte[]'
If anyone could provide an example of how to resolve would be great.
Thanks Frank, I ended up Just creating a new property.
public byte[] Logo
{
get { return Convert.FromBase64String(LogoString); }
}
public string LogoString { get; set; }
I m trying to pass a object to view with viewbag and pass it to javascript parameter in the view
But when comes to assign object to script value it looks like string likes its namespace
in controller:
public ACCIDENT_REPORTS getFilledReportWithEntitiesById(int accidentReport_id)
{
ACCIDENT_REPORTS report = new ACCIDENT_REPORTS();
report = context.ACCIDENT_REPORTS.Include("ACCR_ENTITIES").Where(a => a.ID == accidentReport_id).FirstOrDefault();
return report;
}
ViewBag.Report = DatabaseContext.Current.AccidentReportingRepository.getFilledReportWithEntitiesById(id); //its okey, all data in viewbag
in view:
<script>
debugger
var data = '#ViewBag.Report';
</script>
// in debugger value looks like; var data = 'Application.Database.ACCIDENT_REPORTS;
Why it looks like string ? how can I pass contents of viewbag to javascript value
here is my entity object return type:
public partial class ACCIDENT_REPORTS
{
public ACCIDENT_REPORTS()
{
this.ACCR_ENTITIES = new HashSet<ACCR_ENTITIES>();
}
public decimal ID { get; set; }
public decimal FACILITY_ID { get; set; }
public Nullable<System.DateTime> START_DATE { get; set; }
public Nullable<System.DateTime> END_DATE { get; set; }
public string TITLE { get; set; }
public Nullable<decimal> ACCIDENT_TYPE { get; set; }
public Nullable<decimal> REPORTED_UNDER { get; set; }
public Nullable<decimal> SEVESOII_STATUS { get; set; }
public Nullable<decimal> INDUSTRIAL_ACTIVITY { get; set; }
public string REASON_FOR_REPORTING { get; set; }
public string ACCIDENT_DESCRIPTION { get; set; }
public string SITE_DESCRIPTION { get; set; }
public string UNIT_DESCRIPTION { get; set; }
public string CAUSES_OF_ACCIDENT { get; set; }
public string CONSEQUENCES { get; set; }
public string EMERGENCY_RESPONSE { get; set; }
public string LESSONS_LEARNED { get; set; }
public string ACCIDENTS_INVOLVING { get; set; }
public Nullable<decimal> REPORT_STATUS { get; set; }
public virtual ICollection<ACCR_ENTITIES> ACCR_ENTITIES { get; set; }
}
}
What is the type returned by getFilledReportWithEntitiesById()?
Presumably, it's a Application.Database.ACCIDENT. All the view engine does is invoke .ToString() on what it's given. And the default implementation for .ToString() on any reference type (any child of object basically) is to return the type name.
If you want a custom string representation of your type, then that type needs to override .ToString(). For example:
public override string ToString()
{
return string.Format("{0} - {1}", ID, Name);
}
If the object has an ID property and a Name property then its string representation would then be those values separated by a hyphen (with spaces in between). However you want to structure the string representation of your object would be done within this method.
Conversely, if you don't want it to be a string, but want the JavaScript code to use it as an object, then you want to serialize it to JSON. Something like this:
var data = #Json.Encode(ViewBag.Report);
(You might need to tweak that a little bit, I don't have an environment handy to test it. But you get the idea... To use it as an object in JavaScript code it needs to be serialized to a JavaScript object literal.)
this is the real answer
#Html.Raw(Json.Encode(Model.PlaceStatistic.ToArray()))