I have a problem with my Web App (Razor Pages)
The aim is to return a list of Skills (aka Capabilities) , display on screen then capture a score for each skill before posting back through a WEB API to a DB via a Web Api..
My View:
#page
#model CBSSkillsTracker_WebUI.Pages.ScoreSubmissionFormModel
#{
ViewData["Title"] = "Score Submission Form";
}
<h1>Score Submission Form</h1>
<form method="post">
<table class="table">
<thead>
<tr>
<th scope="col">
Capability ID
</th>
<th scope="col">
Capability Name
</th>
<th scope="col">
Score
</th>
</tr>
</thead>
<tbody>
#for (int index = 0; index < Model.CapabilitiesList.Count; index++)
{
<tr>
<td width="10%">
#Html.HiddenFor(m => m.CapabilitiesList[index].Id)
#Html.DisplayFor(m => m.CapabilitiesList[index].Id)
</td>
<td width="80%">
#Html.HiddenFor(m => m.CapabilitiesList[index].CapabilityName)
#Html.DisplayFor(m => m.CapabilitiesList[index].CapabilityName)
</td>
<td width="10%">
<input type="number" asp-for="Scores[index].Score" min="0" max="5" step="1" name="txtScore" />
</td>
</tr>
}
</tbody>
</table>
<button type="submit">submit</button>
</form>
My Code Behind \ View Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CBSSkillsTracker_WebUI.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Text;
namespace CBSSkillsTracker_WebUI.Pages
{
public class ScoreSubmissionFormModel : PageModel
{
string Baseurl = "https://XXXXX.XXXXXX.net";
[BindProperty(SupportsGet = true)]
public List<CapabilitiesModel> CapabilitiesList { get; set; }
[BindProperty]
public List<ScoreModel> Scores { get; set; }
public async Task<IActionResult> OnGet()
{
using (var client = new HttpClient())
{
//Passing service base url
client.BaseAddress = new Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
//Define request data format
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Sending request to find web api REST service resource using HttpClient
HttpResponseMessage Res = await client.GetAsync("/api/Capabilities");
//Checking the response is successful or not which is sent using HttpClient
if (Res.IsSuccessStatusCode)
{
//Storing the response details recieved from web api
var UserResponse = Res.Content.ReadAsStringAsync().Result;
//Deserializing the response recieved from web api and storing into the Employee list
CapabilitiesList = JsonConvert.DeserializeObject<List<CapabilitiesModel>>(UserResponse);
}
}
return Page();
}
public IActionResult OnPost(List<ScoreModel> Scores)
{
using (var client = new HttpClient())
{
if (!ModelState.IsValid)
{
return Page();
}
List<ScoreModel> scores = Scores.Select(s => new ScoreModel
{
Capability = s.Id,
Score = s.Score,
})
.ToList();
client.BaseAddress = new Uri(Baseurl + "/api/Scores");
//HTTP POST
var httpContent = new StringContent(JsonConvert.SerializeObject(scores), Encoding.UTF8, "application/json");
var postTask = client.PostAsync(client.BaseAddress.ToString(), httpContent);
postTask.Wait();
var result = postTask.Result;
if (result.IsSuccessStatusCode)
{
return Page();
}
else
{ //ModelState.AddModelError(string.Empty, "An Error Occured in 'public ActionResult NewCapability'- Please contact Dev Support ");
}
}
return RedirectToPage ("/Index");
}
}
}
My models:
namespace CBSSkillsTracker_WebUI.Models
{
public class CapabilitiesModel
{
public int Id { get; set; }
public int Category { get; set; }
public string CapabilityName { get; set; }
public string Description { get; set; }
}
}
And
namespace CBSSkillsTracker_WebUI.Models
{
public class ScoreModel
{
public int Id { get; set; }
public int User { get; set; }
public int SubmissionPeriod { get; set; }
public int Capability { get; set; }
public byte Score { get; set; }
}
}
I have an error on the following line of code:
<input type="number" asp-for="Scores[index].Score" min="0" max="5" step="1" name="txtScore" />
The error is : System.NullReferenceException: 'Object reference not set to an instance of an object.'
I think its because the Scores model isnt populated or initialised within the OnGet - because until the user populates the score there are no values to bring back, update before posting.
If I remove that line of code the UI populates correctly with the list of Skills but of course there is no way to capture the scores the user enters for posting..
Can anyone help please? Sorry im new to this so any advice\code welcome
You can try to initialize Scores like this,setting Scores if CapabilitiesList is not null in OnGet:
public class ScoreSubmissionFormModel : PageModel
{
string Baseurl = "https://XXXXX.XXXXXX.net";
[BindProperty(SupportsGet = true)]
public List<CapabilitiesModel> CapabilitiesList { get; set; }
[BindProperty]
public List<ScoreModel> Scores { get; set; }= new List<ScoreModel>();
public async Task<IActionResult> OnGet()
{
using (var client = new HttpClient())
{
//Passing service base url
client.BaseAddress = new Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
//Define request data format
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Sending request to find web api REST service resource using HttpClient
HttpResponseMessage Res = await client.GetAsync("/api/Capabilities");
//Checking the response is successful or not which is sent using HttpClient
if (Res.IsSuccessStatusCode)
{
//Storing the response details recieved from web api
var UserResponse = Res.Content.ReadAsStringAsync().Result;
//Deserializing the response recieved from web api and storing into the Employee list
CapabilitiesList = JsonConvert.DeserializeObject<List<CapabilitiesModel>>(UserResponse);
foreach (var item in CapabilitiesList) {
Scores.Add(new ScoreModel());
}
}
}
return Page();
}
Related
Im new to API,
Below is my scenario, Where i need help. My code may have many issues, kindly help me to learn this. :)
I have an existing API URL, and My objective is to POST request to that existing API URL while submitting a form and get below JSON response
{
"success": true,
"message": "GOOD",
"data": null
}
.cshtml code
#section Scripts {
<script type="text/javascript">
$("#form1").submit(function () {
var Serial = $.post('http://mesappbeta/BE_API_HOME/api/SeriesBlacklist/Req_DBL', $('#form1').serialize())
.success(function () {
var path = Serial.getResponseHeader('Location');
var i = $('<a/>', { href: path, text: path });
$('#message').html(i);
})
.error(function () {
$('#message').html("Error for changes.");
});
return false;
});
</script>
}
<div>
<form Id="form1" method="post" action="http://mesappbeta/BE_API_HOME/api/SeriesBlacklist/Req_DBL" enctype="application/x-www-form-urlencoded">
<asp:Panel ID="pnlGrid" runat="server" Visible="true">
<table>
<tr>
<td style="width: 25%; height: 30px">
<div>
<label for="name">Special Instruction:</label>
<asp:CheckBox ID="CheckBox1" runat="server" />
</div>
</td>
</tr>
<tr>
<td style="width: 25%; height: 30px">
<div>
<label for="name" style="display: block">Notes: </label>
<textarea style="display: block"></textarea>
</div>
</td>
</tr>
<tr>
<td style="width: 25%; height: 30px">
</br>
<div>
<input type="submit" value="Submit" />
#*<button style="width:fit-content" name="StartRequest" value="StartRequest">Start Request</button>*#
</div>
</td>
<th style="border:inherit">
</th>
</tr>
</table>
</asp:Panel>
</form>
</div>
CONTROLLER
using DocumentFormat.OpenXml.ExtendedProperties;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using WebApplication9.Models;
namespace WebApplication9.Controllers
{
using WebApplication9.Models;
public class ChangesController : ApiController
{
static readonly Dictionary<Guid, Change> _changes = new Dictionary<Guid, Change>();
[HttpPost]
[ActionName("Code")]
public HttpResponseMessage PostComplex(Change change)
{
if(ModelState.IsValid && change != null)
{
change.Notes = HttpUtility.HtmlEncode(change.Notes);
var Id = Guid.NewGuid();
_changes[Id] = change;
var response = new HttpResponseMessage(HttpStatusCode.Created)
{
Content = new StringContent(change.Notes)
};
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { action = "type", Id = Id }));
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
[HttpPost]
[ActionName("Decode")]
public HttpResponseMessage PostSimple([FromBody] string value)
{
if(value != null)
{
Change change = new Change()
{
Notes = HttpUtility.HtmlEncode(value)
};
var Id = Guid.NewGuid();
_changes[Id] = change ;
var response = new HttpResponseMessage(HttpStatusCode.Created)
{
Content = new StringContent(change.Notes)
};
response.Headers.Location = new Uri(Url.Link("DefaultApi", new {action = "type", Id=Id }));
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
[HttpGet]
public Change Notes(Guid Id)
{
Change change;
if(_changes.TryGetValue(Id, out change))
{
return change;
}
else
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
}
}
}
Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace WebApplication9.Models
{
public class Change
{
public string Notes { get; set; }
}
}
Webapiconfig.cs
namespace WebApplication9
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
}
}
I TRIED : POST existing API URL through Submit button of a webform.
Expected to get below response :
{
"success": true,
"message": "GOOD",
"data": null
}
But getting below error message :
Hi #Guru you can add generic API response wrapper to return you response.
public class ServiceResponse<T>
/// <summary>
/// Generic wrapper for web api response.
/// </summary>
/// <typeparam name="T"></typeparam>
public class ServiceResponse<T>
{
public T Data { get; set; }
public bool Success { get; set; } = true;
public string Message { get; set; } = null;
public string Error { get; set; } = null;
public List<string> ErrorMessages { get; set; } = null;
}
How to use it:
ServiceResponse<NoteModel> _response = new();
_response.Success = true;
_response.Data = NoteModel;
_response.Message = "Created";
return _response;
Here is an example for both HttpResponseMessage and IHttpActionResult. I have tested both and they work.
[HttpPost]
[ActionName("Code")]
public HttpResponseMessage PostComplex(SampleViewModel change)
{
if (ModelState.IsValid && change != null)
{
ServiceResponse<SampleViewModel> _response = new ServiceResponse<SampleViewModel>();
var newGuid = Guid.NewGuid().ToString();
change.Id = newGuid;
if (!string.IsNullOrWhiteSpace(change.Id))
{
// ...
_response.Data = change;
_response.Success = true;
_response.Message = "Created";
return Request.CreateResponse(_response);
}
// ...
_response.Data = change;
_response.Success = false;
_response.Message = "Failed";
return Request.CreateResponse(_response);
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
[HttpPost]
[ActionName("Code")]
public IHttpActionResult PostComplex2(SampleViewModel change)
{
if (ModelState.IsValid && change != null)
{
ServiceResponse<SampleViewModel> _response = new ServiceResponse<SampleViewModel>();
var newGuid = Guid.NewGuid().ToString();
change.Id = newGuid;
if (!string.IsNullOrWhiteSpace(change.Id))
{
// ...
_response.Data = change;
_response.Success = true;
_response.Message = "Created";
return Ok(_response);
}
// ...
_response.Data = change;
_response.Success = false;
_response.Message = "Failed";
return Ok(_response);
}
else
{
return BadRequest();
}
}
public class SampleViewModel
{
[Required]
[MinLength(10)]
[MaxLength(100)]
[Display(Name = "Ask Magic 8 Ball any question:")]
public string Question { get; set; }
public string Id { get; set; }
//See here for list of answers
public string Answer { get; set; }
}
public class ServiceResponse<T>
{
public T Data { get; set; }
public bool Success { get; set; }
public string Message { get; set; }
public string Error { get; set; }
public List<string> ErrorMessages { get; set; }
}
I have this property in my PageModel:
public List<string> PhonenumbersFromExcel { get; set; }
I want to show data imported from Excel in my view. How can I assign my data in order to show from controller.
My question is: How can I do this? and is there any other way to solve it?
Below you can see my controller:
public virtual async Task<IActionResult> ImportPhonenumbersFromExcel(Model model, IFormFile importexcelfile, int currentFestivalId)
{
var phonenumbersFromExcel = new List<string>();
try
{
if (importexcelfile != null && importexcelfile.Length > 0)
{
var result = await _importManager.ImportPhonenumbersFromXlsxAsync(importexcelfile.OpenReadStream());
foreach (var item in result.Distinct())
{
var validPhonenumber = "";
// ensure given phonenumber starts with 0
if (!item.StartsWith("0"))
{
string zeroAdded = "0" + item;
validPhonenumber += zeroAdded;
}
bool isValid = true;
if (!CommonHelper.IsValidMobile(validPhonenumber))
isValid = false;
if (!CommonHelper.IsValidPhoneNumber(validPhonenumber))
isValid = false;
if (isValid)
phonenumbersFromExcel.Add(validPhonenumber);
}
model.PhonenumbersFromExcel.AddRange(phonenumbersFromExcel);
}
_notificationService.SuccessNotification(await _localizationService.GetResourceAsync("Admin.Festival.Phonenumbers.Imported"));
return RedirectToAction("Edit", new { id = currentFestivalId });
}
catch (Exception em)
{
await _notificationService.ErrorNotificationAsync(em);
return RedirectToAction("Edit", new { id = currentFestivalId });
}
}
Do you want to read data from Excel and display it on the page? You can use ExcelDataReader.
I did a simple test, you can refer to it.
Install related Nuget packages: ExcelDataReader and System.Text.Encoding.CodePages.
Model:
public class Phonenumber
{
public List<string> PhonenumbersFromExcel { get; set; }
}
Controller:
public class PhonenumberController : Controller
{
[HttpGet]
public IActionResult Index(Phonenumber phonenumber = null)
{
phonenumber = phonenumber == null? new Phonenumber() : phonenumber;
return View(phonenumber);
}
[HttpPost]
public IActionResult Index(IFormFile excelFile, [FromServices] IHostingEnvironment hostingEnvironment)
{
//I created a folder called files under wwwroot
string fileName = $"{hostingEnvironment.WebRootPath}\\files\\{excelFile.FileName}";
using (FileStream fileStream = System.IO.File.Create(fileName))
{
excelFile.CopyTo(fileStream);
fileStream.Flush();
}
var phoneNumber = this.GetNumber(excelFile.FileName);
return View(phoneNumber);
}
private Phonenumber GetNumber(string fName)
{
Phonenumber phonenumberModel = new Phonenumber();
phonenumberModel.PhonenumbersFromExcel = new List<string>();
var fileName = $"{Directory.GetCurrentDirectory()}{#"\wwwroot\files"}" + "\\" + fName;
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
using (var stream = System.IO.File.Open(fileName, FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
while (reader.Read())
{
phonenumberModel.PhonenumbersFromExcel.Add(reader.GetValue(0).ToString());
}
}
}
return phonenumberModel;
}
}
View:
#model Project.Models.Phonenumber
<div>
<form asp-action="Index" method="post" enctype="multipart/form-data">
<input type="file" name="excelFile" />
<input type="submit" value="Import" />
</form>
#if (Model.PhonenumbersFromExcel !=null &&Model.PhonenumbersFromExcel.Count()>0)
{
<hr />
<table cellpadding="0" cellspacing="0" border="1" class="table">
#foreach (var phonenumber in Model.PhonenumbersFromExcel)
{
<tr>
<td>#phonenumber</td>
</tr>
}
</table>
}
</div>
Test Result:
I created a ASP.NET RazorPage project to post a request to another website on the web. I want to display response on the page but no luck. Any idea?
Here is the cshtml file content
#page
#model Emulator.Pages.AddSensorsModel
#{
}
<a asp-page="/Index">Back</a>
<form method="post">
<p>sensor-prefix:<input id="sensor-prefix" type="text" name="SensorPrefix" /></p>
<p>sensor-count:<input id="sensor-count" type="number" name="SensorCount" /></p>
<p><button id="submit-btn" type="submit" asp-page-handler="AddSensors" class="btn btn-primary">Add Sensors</button></p>
</form>
<p>#Model.JsonString</p>
Here is the cs content
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Text;
using System.Net;
namespace ScovilleEmulator.Pages
{
public class AddSensorModel
{
[BindProperty]
public string SensorPrefix { get; set; }
[BindProperty]
public string SensorCount { get; set; }
}
public class AddSensorsModel : PageModel
{
public string JsonString { get; set; }
public async Task OnGetAsync()
{
}
public async void OnPostAddSensors(AddSensorModel sensors)
{
var client = new HttpClient();
string url = "http://localhost:8090/envirovue/start";
string body = #"""envirovue"": {
""sensors"": {
""mac_prefix"": """ + sensors.SensorPrefix + #""",
""count"": " + sensors.SensorCount + #"
}
}";
var httpResponseMessage = await client.PostAsync(url, new StringContent(body, Encoding.UTF8, "application/json"));
if (httpResponseMessage.StatusCode == HttpStatusCode.OK)
{
string response = await httpResponseMessage.Content.ReadAsStringAsync();
JsonString = response;
}
}
}
}
I've tried to update the JsonString to a static string lik hello world and it's ok. But it can not display the response content.
I have a question how to solve my problem. There is a table with items. Each item has a status "open" or "closed". For instance, 9 items with "closed" status and 14 ones with "open". I need to find the difference between open and closed items (14 - 9 = 5). How can I do it with help of ViewBag? As I understood, it is required to write "count" function in controller and transmit the result to View via ViewBag. But I don't know how to write this code. The result should be shown on the View page.
Request.cs (Model):
public class Request
{
public int Id { get; set; }
public string Name { get; set; } = "";
public string Status { get; set; } = "";
}
Controller.cs:
public IActionResult Requests()
{
var Requests = _repo.GetAllRequests();
return View(Requests);
}
Repository:
public Request GetRequest(int id)
{
return _ctx.Requests.FirstOrDefault(c => c.Id == id);
}
public List<Request> GetAllRequests()
{
return _ctx.Requests.ToList();
}
View:
<div>
<table>
#foreach (var request in Model)
{
<tr>
<th>#request.Name</th>
<th>#request.Status</th>
</tr>
}
</table>
</div>
private StatisticScore()
{
var openCount =_ctx.Requests.Where(m=> m.Status == "Open").Count();
var closedCount = _ctx.Requests.Where(m=> m.Status == "Closed").Count();
ViewBag.Difference = openCount - closedCount
}
<label> Difference </label> #ViewBag.Difference
Also, I suggest you; Do not use status fields as strings. It will be easier for you if you keep it as an enum.
You would pass a predicate to Count to filter the requests by status:
public IActionResult Requests()
{
var requests = _repo.GetAllRequests();
ViewBag.OpenRequests = requests.Count(r => r.Status == "open");
ViewBag.ClosedRequests = requests.Count(r => r.Status == "closed");
return View(requests);
}
However, rather than using the ViewBag you could create a view model to hold all the information/data required by the view:
// ViewModel
public class RequestViewModel
{
public List<Request> Requests { get; set; }
public int OpenRequests { get; set; }
public int ClosedRequests { get; set; }
}
// Controller
public IActionResult Requests()
{
var requests = _repo.GetAllRequests();
var viewModel = new RequestViewModel();
viewModel.OpenRequests = requests.Count(r => r.Status == "open");
viewModel.ClosedRequests = requests.Count(r => r.Status == "closed");
viewModel.Requests = requests;
return View(viewModel);
}
// View: set the model for the view
#model Project.Namespace.RequestViewModel
...
<div>
<div>Open Requests: #model.OpenRequests</div>
<div>Closed Requests: #model.ClosedRequests</div>
<div>Difference/delta: #(model.OpenRequests - model.ClosedRequests)</div>
</div>
I am trying to get the closing value from the first and second object from my api response and compare them and then display the a string depending on the comparison on the html page
(I have removed my personal api key and replaced it with 'your_api_key')
The response I am getting from the api is as follows;
{"Response":"Success","Type":100,"Aggregated":false,"Data":[{"time":1548191280,"close":1.13,"high":1.13,"low":1.13,"open":1.13,"volumefrom":0,"volumeto":0},{"time":1548191340,"close":1.13,"high":1.13,"low":1.13,"open":1.13,"volumefrom":0,"volumeto":0}],"TimeTo":1548191340,"TimeFrom":1548191280,"FirstValueInArray":true,"ConversionType":{"type":"direct","conversionSymbol":""},"RateLimit":{},"HasWarning":false}
I have tried to use an if statement but I am getting errors, I believe the problem lies in how I am trying to access the list
Currencies.cs
public class DatumEurUSD
{
public double CLOSE { get; set; }
public double HIGH { get; set; }
public double LOW { get; set; }
public double OPEN { get; set; }
public string MOVEMENT { get; set; }
}
public class RootObjectEurUSD
{
public List<DatumEurUSD> Data { get; set; }
public double OldUSD { get => Data.First().CLOSE; set => OldUSD = value; } // value of USD one minute ago
public double NewUSD { get => Data.ElementAt(1).CLOSE; set => NewUSD = value; } // current value of USD
if(OldUSD == NewUSD)
{
DatumEurUSD.Movement.set("NONE")
}
else if(OldUSD > NewUSD)
{
DatumEurUSD.Movement.set("DOWN")
}
else if(OldUSD < NewUSD)
{
DatumEurUSD.Movement.set("UP")
}
}
HomeController.cs
public async Task<ActionResult> Currencies()
{
var req = WebRequest.Create(#"https://min-api.cryptocompare.com/data/pricemulti?fsyms=EUR&tsyms=USD,JPY,GBP,CHF,CAD,AUD,NZD&api_key=your_api_key");
var reqEurUSD = WebRequest.Create(#"https://min-api.cryptocompare.com/data/histominute?fsym=EUR&tsym=USD&limit=1&api_key=your_api_key");
//var reqEurAVG = WebRequest.Create(#"");
var r = await req.GetResponseAsync().ConfigureAwait(false);
var rEurUSD = await reqEurUSD.GetResponseAsync().ConfigureAwait(false);
//var rEurAVG = await reqEurAVG.GetResponseAsync().ConfigureAwait(false);
var responseReader = new StreamReader(r.GetResponseStream());
var responseData = new JsonTextReader(responseReader);
var responseReaderEurUSD = new StreamReader(rEurUSD.GetResponseStream());
var responseDataEurUSD = new JsonTextReader(responseReaderEurUSD);
//var responseReaderEurAVG = new StreamReader(rEurAVG.GetResponseStream());
//var responseDataEurAVG = new JsonTextReader(responseReaderEurAVG);
var serializer = new JsonSerializer();
var d = serializer.Deserialize<RootObjectEUR>(responseData);
var dEurUSD = serializer.Deserialize<RootObjectEurUSD>(responseDataEurUSD);
//var dEurAVG = serializer.Deserialize<RootObjectEurAVG>(responseDataEurUSD);
dynamic mymodel = new ExpandoObject();
mymodel.Eur = d.EUR;
mymodel.EurUSD = dEurUSD.Data;
return View(mymodel);
}
Currencies.cshtml
#model dynamic
<h1>Most Common Currency Exchanges</h1>
<table border="1">
<th>Currency</th>
<th>Rate</th>
<th>Movement</th>
<th>Open</th>
<th>Close</th>
<th>Date</th>
<tr>
<td>EUR/USD</td>
<td>#Model.Eur.USD</td>
<td>#Model.Data.MOVEMENT</td>
<td></td>
<td></td>
<td>#DateTime.Now</td>
</tr>
I am currently currently getting an error in my if statement for invalid token and the variables do not exist in the current context.
I would like the #Model.Data.MOVEMENT to display the correct string according to the if condition.