我正在尝试使用 Google API 进行转换。但是我得到并且索引超出范围错误并且表单集合没有按照我想要的方式收集数据(金额,货币从,货币到)。我究竟做错了什么?
汇率控制器:
public ActionResult Index()
{
IEnumerable<CommonLayer.Currency> currency = CurrencyManager.Instance.getAllCurrencies().ToList();
return View(currency);
}
[HttpPost]
public ActionResult Index(FormCollection fc)
{
if (ModelState.IsValid)
{
WebClient web = new WebClient();
string url = string.Format("http://www.google.com/ig/calculator?hl=en&q={2}{0}%3D%3F{1}", (string)fc[1].ToUpper(), (string)fc[2].ToUpper(), (string)fc[0]);
string response = web.DownloadString(url);
Regex regex = new Regex("rhs: \\\"(\\d*.\\d*)");
Match match = regex.Match(response);
decimal rate = System.Convert.ToDecimal(match.Groups[1].Value);
ViewBag["rate"] = (string)fc[0] + " " + (string)fc[1] + " = " + rate + " " + (string)fc[2];
}
return View();
}
汇率视图:
@model IEnumerable<CommonLayer.Currency>
@{
ViewBag.Title = "Exchange Rates";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@Html.Partial("_ExchangeRatePartial");
局部视图:
@model IEnumerable<CommonLayer.Currency>
<br /> <br />
@Html.BeginForm())
{
Convert: <input type="text" size="5" value="1" />
@Html.DropDownList("Currency", Model.Select(p => new SelectListItem{ Text = p.ID, Value = p.Name}))
to
@Html.DropDownList("Currency", Model.Select(p => new SelectListItem { Text = p.ID, Value = p.Name}))
<br /> <br /> <input type="submit" name="Convert" />
}
@if(ViewData["rate"] != null)
{
@ViewData["rate"]
}