MVC检索和发送数据 - 货币转换

时间:2013-05-07 14:24:12

标签: asp.net-mvc google-api

我正在尝试使用Google API进行转换。但是我得到了并且索引超出了范围错误,并且表单集合没有收集我想要的数据(amount,currencyFrom,currencyTo)。我做错了什么?

汇率管制员:

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"]
    }

1 个答案:

答案 0 :(得分:1)

您的输入被视为复杂对象。最好使用viewmodel,这样你也可以从模型绑定器中受益。

public class CurrencyViewModel {
    public string ConversionRate {get;set;}
    public IList<int> Currencies {get;set;}
    public IEnumerable<CommonLayer.Currency> CurrencyList {get;set;}
}

然后您需要将视图更改为

@model CurrencyViewModel 
Convert: @Html.TextboxFor(m=>m.ConversionRate, new { @size="5" } />
@Html.DropDownList("Currencies", 
    Model.CurrencyList.Select(p => 
        new SelectListItem{ Text = p.ID, Value = p.Name}))
@Html.DropDownList("Currencies", 
    Model.CurrencyList.Select(p => 
        new SelectListItem{ Text = p.ID, Value = p.Name}))

然后你的控制器方法

public ActionResult Index() {
    var currency = CurrencyManager.Instance.getAllCurrencies().ToList();
    return View(new CurrencyViewModel { CurrencyList = currency });
}

[HttpPost]
public ActionResult Index(CurrencyViewModel input)
{
    // you can then access the input like this
    var rate = input.ConversionRate;
    foreach(var currency in input.Currencies) {
        var id = currency; 
        // currency is an int equivalent to CommonLayer.Currency.ID
    }
}