简体   繁体   English

通过API消费价值

[英]Consuming Value from API

I am new to MVC and has trying to develop a money exchange which has a text box and two drop lists of the currencies to exchange. 我是MVC的新手,并且正在尝试开发一个货币交换,该货币交换具有一个文本框和两个要交换货币的下拉列表。 I used the API web service that has a table holds the currencies names, country and values. 我使用了具有表的API Web服务,该表包含货币名称,国家和值。 My problem is to calculate the value from the API once the user post the action method after inserting the amount in the ConversionRate as I always get a 0 value! 我的问题是,一旦用户在ConversionRate中插入金额后发布操作方法,就从API计算值,因为我总是得到0值! What am I doing wrong here? 我在这里做错了什么?

Index Action method 索引操作方法

  [HttpPost]
        public ActionResult Index(Currencies cur)
        {
            if (cur.ConversionRate.Equals(null))
            {
                ModelState.AddModelError("", "Please enter a numeric value");
            }

            if (cur.FromCurrencyId == cur.ToCurrencyId)
            {
                //do something if same currecnies and return.
                ModelState.AddModelError("", "Can't make the conversion for the same curreny");
            }
            else
            {
                if (ModelState.IsValid)
                {
                    CurrenciesClient Cur = new CurrenciesClient();
                    var listCurrency = Cur.findAll().ToList();

                    Currencies model = new Currencies();
                    model.FromCurrencies = new SelectList(listCurrency,"FromCurrencyId", "CurrencyName","Value");
                    model.ToCurrencies = new SelectList(listCurrency, "ToCurrencyId", "CurrencyName","Value" );

                    ViewBag.TheResult = listCurrency.Where(c => c.FromCurrencyId == cur.FromCurrencyId && c.ToCurrencyId == cur.ToCurrencyId).FirstOrDefault().ConversionRate * cur.Value;

                    return PartialView("_CurrencyValue");
                }
            }
            return View();
        }

API web service CurrenciesClient API Web服务CurrenciesClient

public class CurrenciesClient 
    {
        private string base_Url = "http://localhost:51646/api/";

        public IEnumerable<Currencies> findAll()
        {
            try
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(base_Url);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = client.GetAsync("currencies").Result;
                if (response.IsSuccessStatusCode)
                {
                    var resposeData = response.Content.ReadAsStringAsync().Result;
                    var Currency = JsonConvert.DeserializeObject<List<Currencies>>(resposeData);
                    return Currency;
                }
                return null;
            }
            catch
            {
                return null;
            }
        }
    }

Currencies VM 货币VM

  public class Currencies
    {
        public int Id { get; set; }

        [Required(ErrorMessage = " message")]
        public int FromCurrencyId { get; set; }
        public SelectList FromCurrencies { get; set; }

        [Required]
        public int ToCurrencyId { get; set; }
        public SelectList ToCurrencies { get; set; }

        public string CurrencyName { get; set; }

        public string CurrencyCountry { get; set; }


        [Required(ErrorMessage ="Please enter a numeric value")]
        public decimal ConversionRate { get; set; }  

        public decimal Value { get; set; }

        public SelectList AvailableCurrencies { get; set; }
    }

Index View 索引检视

@model Project.ViewModels.Currencies

@{
    ViewBag.Title = "Index";
}
<div id="ConversionSection">

        @using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "post", InsertionMode = InsertionMode.Replace, UpdateTargetId = "ConversionSection" }))
        {
            @Html.AntiForgeryToken()

            @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            @Html.TextBoxFor(m => m.ConversionRate, new { @class = "form-control" })

            @Html.DropDownListFor(m => m.FromCurrencyId, Model.FromCurrencies as IEnumerable<SelectListItem>, new { @class = "form-control" })
            @Html.DropDownListFor(m => m.ToCurrencyId, Model.ToCurrencies as IEnumerable<SelectListItem>, new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.ToCurrencyId, "", new { @class = "text-danger" })
            <br />
            <button type="submit" class="btn btn-primary">Convert</button>
        }

</div>
@section scripts{
   <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
}

You are allowing the user to enter the Conversion Rate in the form, but then also looking this up in the API. 您允许用户在表单中输入转化率,然后在API中进行查找。 This is not logical. 这是不合逻辑的。 You don't want the user to enter the Conversion Rate themselves - this is the data you are keeping in order to calculate the exchange. 您不希望用户自己输入转化率-这是您为了计算交换而保留的数据。

What you aren't getting the user to enter is the amount of currency they want to exchange. 您没有让用户输入的是他们想要兑换的货币量。 This is held in the "Value" field in your ViewModel. 这保存在ViewModel的“值”字段中。 Since this is not entered, it's always defaulting to 0, and this is why when you do ConversionRate * cur.Value it always returns 0. (The ConversionRate in that equation is, correctly, the one returned by the API, not the one entered by the user). 由于未输入该值,因此它始终默认为0,这就是为什么当您执行ConversionRate * cur.Value它始终返回0。(该等式中的ConversionRate正确地是API返回的值,而不是输入的由用户)。

To solve, simply change 要解决,只需更改

@Html.TextBoxFor(m => m.ConversionRate, new { @class = "form-control" })

to

@Html.TextBoxFor(m => m.Value, new { @class = "form-control" })

Your UI should probably also contain a label telling the user what to enter! 您的UI可能还应该包含一个标签,告诉用户输入什么!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM