简体   繁体   中英

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. I used the API web service that has a table holds the currencies names, country and values. 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! 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

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

  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. 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. 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).

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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