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



我正在尝试使用谷歌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"]
    }

您的输入被认为是一个复杂对象。最好使用视图模型,这样您还可以从模型绑定器中获益。

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

相关内容

  • 没有找到相关文章

最新更新