【发布时间】:2021-02-24 20:01:52
【问题描述】:
所以,我有一个用于货币兑换的网络应用程序。我需要的是在不重新加载页面的情况下获得转换结果。在这个应用程序中,我从 api 获取数据。提交表单后页面开始重新加载并再次调用 HttpGet 方法。因为它,我得到了例外。有没有什么办法可以换币不重载页面?
型号
public class ExchangeRate
{
[JsonProperty("rates")]
public Dictionary<string, double> Rates { get; set; }
[JsonProperty("base")]
public string Base { get; set; }
[JsonProperty("date")]
public DateTimeOffset Date { get; set; }
}
控制器
public class HomeController : Controller
{
[HttpGet]
public async Task<ActionResult> Index()
{
ExchangeRate curencyInfo = new ExchangeRate();
using (HttpClient client = new HttpClient())
{
curencyInfo = await client.GetFromJsonAsync<ExchangeRate>("https://api.exchangeratesapi.io/latest?base=USD");
}
return View(curencyInfo);
}
[HttpPost]
public ActionResult Index(decimal fromCurrency, decimal toCurrency, decimal fromValue)
{
var toValue = toCurrency / fromCurrency * fromValue;
decimal result = Math.Round(toValue, 2);
ViewBag.toValue = result;
return View();
}
}
查看
@model WebCurrencyConverter.Models.ExchangeRate
@{
ViewData["Title"] = "Currency Converter";
}
<h1>Currency Converter</h1>
<form method="post">
<select name="fromCurrency">
@foreach (var itemFrom in Model.Rates)
{
<option value="@itemFrom.Value">@itemFrom.Key</option>
}
</select>
<input type="hidden" value="@Model.Rates" />
<select name="toCurrency">
@foreach (var itemTo in Model.Rates)
{
<option value="@itemTo.Value">@itemTo.Key</option>
}
</select>
<input type="number" name="fromValue" step="any" />
<input type="number" name="toValue" value="@ViewBag.toValue" />
<input type="submit" class="btn btn-success" value="Convert" />
</form>
【问题讨论】:
-
当然,有多种方式可以在不重新加载网页的情况下与服务器进行通信。一些基础研究会教你有关 XMLHttpRequest、Fetch API、Web 套接字等的知识。你研究过这些吗?试图实施它们?您在实施过程中遇到了哪些问题?
-
嗨@James,请检查我的回答。如果有任何问题,您可以跟进让我知道。如果它帮助您解决问题,请记住接受作为答案。谢谢!参考: How to accept as answer.
标签: asp.net asp.net-mvc api rest asp.net-core