【问题标题】:Currency exchange without reloading page无需重新加载页面的货币兑换
【发布时间】: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


【解决方案1】:

因此我得到了例外。有没有什么办法可以换币不重载页面?

为了避免重新加载页面,我认为你可以使用 ajax 来发布数据。

这是一个完整的工作演示:

查看:

@model 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" />   //change here.....

      //change the type to button and add the id for button
    <input type="button" class="btn btn-success" id="convert" value="Convert" />

</form>

视图中的 Js:

@section Scripts
{
<script>
    $("#convert").click(function () {
        console.log($('form').serialize());
        $.ajax({
            url: "/Home/Index",
            type: "Post",
            data: $('form').serialize(),
            success: function (data) {
                console.log(data.result);
                $('input[name="toValue"]').val(data.result);
            }
        })
    })
</script>
}

控制器:

[HttpGet]
public async Task<ActionResult> Index()
{
    ExchangeRate curencyInfo = new ExchangeRate();
    curencyInfo.Rates = new Dictionary<string, double>() { };
    curencyInfo.Rates.Add("US", 1);
    curencyInfo.Rates.Add("Euro", 0.82);
    return View(curencyInfo);
}

[HttpPost]
public JsonResult Index(decimal fromCurrency, decimal toCurrency, decimal fromValue)
{
    var toValue = toCurrency / fromCurrency * fromValue;
    decimal result = Math.Round(toValue, 2);
    return Json(new { result = result });
}

结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 2013-08-05
    • 2012-06-10
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多