I am trying to learn how to use .NET and React and make a single page application where the React front end speaks to the .NET back end. I have decided to create a simple thermostat application where the user can view a thermostat temperature and press buttons which will increase and decrease that temperature. Before I even get that far though I am struggling to get the data from my Controller class to display on my front end. Here is my code:
ThermostatController.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace ThermostatDotNet.Controllers
{
[Route("api/[controller]")]
public class ThermostatController : Controller
{
private int _Temperature { get; set; }
public ThermostatController(int _temperature)
{
_Temperature = _temperature;
}
[HttpGet, Route("GetTemp")]
public int GetTemp()
{
return _Temperature;
}
[HttpGet, Route("Increase")]
public int Increase()
{
_Temperature += 1;
return _Temperature;
}
}
}
Thermostat.js
import React, { Component } from 'react';
export class Thermostat extends Component {
state = {
temp: ""
}
displayTemp() {
fetch("api/Thermostat/GetTemp")
.then(response => response.text())
.then(data => {
this.setState({ temp: data });
});
}
render () {
return (
<div>
<h1>Thermostat</h1>
<p>The temperature is:{this.state.temp}</p>
</div>
);
}
}
The problem I am having is that I want to display the current temperature of the Thermostat when the user visits the application. I am not sure how to create that new thermostat and display the temperature in my React code? I have looked at other Stack Overflow answers but am still finding it difficult to implement here (I'm very new to React and .NET). Can anyone help? Thank you :)
UPDATE
After receiving the following error InvalidOperationException: Unable to resolve service for type 'System.Int32' while attempting to activate 'ThermostatDotNet.Controllers.ThermostatController'. I managed to fix this by using an interface and implementing this:
[Route("api/[controller]")]
public class ThermostatController : Controller
{
private readonly ITemperature _temperature;
private int _Temperature { get; set; }
public ThermostatController(ITemperature temperature)
{
_temperature = temperature;
}
[HttpGet, Route("GetTemp")]
public int GetTemp()
{
return _Temperature;
}
}
First of all you need to return number from your controller like this.
Using return Ok();
[Route("api/[controller]")]
public class ThermostatController : Controller
{
public ThermostatController()
{
}
[HttpGet, Route("GetTemp")]
public int GetTemp()
{
return Ok(1);
}
}
Update: Then in your react use componentDidMount make sure you console.log(data) to see the data then use data.something to display data
componentDidMount() {
fetch("api/Thermostat/GetTemp")
.then(data => {
console.log(data);
this.setState({ temp: data });
});
}
You can read a document here
Related
I want to pass configuration values from appsettings.json in ASP.Net Core / 5.0 to a client-side plain JavaScript code; the parameters will not be changed after setup. What is the easiest way to do it?
You can:
1 - expose a controller action to fetch configuration and call the backend from JS.
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly IConfiguration _config;
public ValuesController(IConfiguration config)
{
_config = config;
}
[HttpGet("config")]
public ActionResult Get()
{
var data = new
{
SomeValue = _config["SomeValue"]
};
return Ok(data);
}
}
fetch('api/values/config').then(function(response) {
console.log(response);
})
2 - write the vales directly to the HTML page.
public class HomeController : Controller
{
private readonly IConfiguration _config;
public HomeController(IConfiguration config)
{
_config = config;
}
public IActionResult Index()
{
var model = new HomeIndexModel
{
SomeValue = _config["SomeValue"]
};
return View(model);
}
}
Index.cshtml
#model MyApp.Controllers.HomeIndexModel;
<script type="text/javascript">
window['portalData'] = #Json.Serialize(Model);
</script>
<app-root></app-root>
I have the following lightning web component to read a JSON string and display them in Contact record Details page. Please note that I am new to lighting web components and making a considerable amount of effort to learn.
MyComponent.html
<template>
<lightning-record-form
object-api-name={contactObject}
fields={myFields}
onsuccess={handleContactCreated} onload={handleContactInitialized} >
</lightning-record-form>
</template>
MyComponent.js
import { LightningElement, wire, track } from 'lwc';
import findDetails from
'#salesforce/apex/JSONDemoController.getContactWithRelatedDataById';
import CONTACT_OBJECT from '#salesforce/schema/Contact';
import NAME_FIELD from '#salesforce/schema/Contact.Name';
import TEST_FIELD from '#salesforce/schema/Contact.TestField__c';
import SPOUSE_FIELD from '#salesforce/apex/ResponseJSONWrapper.spouse';
import ADDRESS_FIELD from
'#salesforce/apex/ResponseJSONWrapper.mailingAddress';
export default class ContactCreator extends LightningElement {
contactObject = CONTACT_OBJECT;
myFields = [SPOUSE_FIELD,ADDRESS_FIELD];
#track contacts;
#track error;
handleContactCreated(){
// Run code when account is created.
}
handleContactInitialized(){
findDetails()
.then(result => {
var responseObj = JSON.parse(result.getReturnValue());
this.SPOUSE_FIELD = responseObj.spouse;
this.ADDRESS_FIELD = responseObj.mailingAddress;
})
.catch(error => {
this.error = error;
});
myFields = [SPOUSE_FIELD,ADDRESS_FIELD];
}
}
JSONDemoController.cls
public class JSONDemoController {
#AuraEnabled
public static String getContactWithRelatedDataById() {
String response = '';
ResponseJSONWrapper wrapper = new ResponseJSONWrapper();
wrapper.spouse = 'Test Spouse';
wrapper.mailingAddress = 'Test Address';
response = JSON.serialize(wrapper);
return response;
}
}
ResponseJSONWrapper.cls
public with sharing class ResponseJSONWrapper {
public String spouse;
public String contactRecordType;
public Date birthDate;
public String mobile;
public String mailingAddress;
public String otherAddress;
public String languages;
public String level;
public String Description;
}
But I don't get the values I have hard coded in the lightning component when it is rendered. Nothing is there it's empty.
Can someone help to point out where I am going wrong ?
Change this line:
var responseObj = JSON.parse(result.getReturnValue());
To:
var responseObj = JSON.parse(result);
getReturnValue() is for Aura components.
You don't actually need to serialize the wrapper in apex and then parse in the component explicitly, the framework does the job by itself!
public class JSONDemoController {
#AuraEnabled //change return type to ResponseJSONWrapper
public static ResponseJSONWrapper getContactWithRelatedDataById() {
String response = '';
ResponseJSONWrapper wrapper = new ResponseJSONWrapper();
wrapper.spouse = 'Test Spouse';
wrapper.mailingAddress = 'Test Address';
return wrapper; //return the wrapper itself
}
and in .js file
findDetails()
.then(result => {
var responseObj = result;
...
})
This way the code will be less cluttered with not-needed code :)
I've developed a restful webservice which displays a simple data using below code.
package com.mike;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class MessageController {
#RequestMapping(value="/message",method=RequestMethod.GET)
public Message print(){
return new Message(1,"Hello Mike!!");
}
}
and the bean is as follows....
package com.mike;
public class Message {
private int id;
private String message;
public Message(int id, String message){
this.id=id;
this.message=message;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMesssage(String message) {
this.message = message;
}
}
now I want to display this data in an Nodejs application, so I wrote a file named app.js and wrote the following code to display data in the console.and it worked fine. but i don't know how to integrate this nodejs application with reactjs UI so that i can display in on a web page. so please kindly help me, I am new to both node and react.the code for app.js is below...
var http=require('http');
var extServerOptions={
host:'localhost',
port:'8080',
path:'/message',
method:'GET'
};
var mes=[];
var x;
var text="";
function get(){
http.request(extServerOptions,function (res){
res.setEncoding('utf8');
res.on('data',function(data){
mes=JSON.parse(data);
console.log(mes);
for(x in mes){
text+=mes[x]+" ";
};
console.log(text);
});
}).end();
};
get();
please kindly say me the stepps i need to do in order to display data in a react page.
I'm trying to think of a pattern I can use.
I want to be able to have a middleman module that takes in a kind of state of a game. Given that state, call a certain method that resides in anotehr module.
What pattern could I use for this?
For example, I want to be able to take in a state of "computer always wins" and based on that state type, I'll call someOtherModule.makeComputerMove(). In the future maybe we want to be able to set the game to a mode where the computer doesn't always win. Well then we could send in a state of "normal game" or something like that which would just call computerAlwaysWins.makeComputerMove() from a different use case module such as normalGame.makeComputerMove()
get the idea?
I can't think of any patterns to provide such a thing...probably because I don't know a lot of them.
You should use State pattern probably with combination of Observer.
public class GameStateContext {
PlayerState Player {get;set; }
// other properties that need to be shared
}
public interface IGameController {
void GoToState(State state)
}
public interface IGameState {
void Start();
void Update();
}
public abstract class GameStateBase : IGameState {
protected GameStateContext _context;
protected IGameController _parent;
public GameStateBase(GameStateContext context, IGameController parent) {
this._context = context;
this._parent = parent;
}
public virtual void Start() {
}
public virtual void Update() {
}
}
public class BonusLevelState : GameStateBase {
public public MainMenuState (GameStateContext context, IGameController parent) : base (context, parent) {
}
public override void Update() {
if(_context.Player.Health == 0) {
_parent.GoToState(GameStates.GameOver);
}
}
}
public GameController : IGameController {
public enum GameStates {
BonusLevel,
InitialState,
....
}
private IGameState currentState;
public GameController() {
// create diferent states
...
currentState = GetState(GameStates.InitialState);
}
public void Update {
currentState.Update();
}
public GoToState(State state) {
currentState = GetState(state);
}
}
I hope you catch an idea, good luck!
In my index.html page, a variable in the script is hard coded. I want to get it from application.properties file but have no idea how to. It would helpful if anyone could provide me a solution.
I have attached the example. Hope to help.
Application
#SpringBootApplication
public class Application {
public static void main(String... args) {
SpringApplication.run(Application.class);
}
}
PropertiesController
#RestController
public class PropertiesController {
#Autowired
private UIProperty uiProperty;
#RequestMapping("properties")
public UIProperty getProperties() {
return uiProperty;
}
}
UIProperty
#Component
#ConfigurationProperties(prefix = "ui.label")
public class UIProperty {
private String user;
private String password;
public void setUser(String user) {
this.user = user;
}
public String getUser() {
return user;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return password;
}
}
application.properties
ui.label.user=user
ui.label.password=password
database.user=
database.password=
I'd create a RestController to expose ConfigurationProperties. But be sure to properly secure it as well as limit in its scope not to disclose confidential data like db access credentials.