0

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

1 回答 1

1

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

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
    }
}
于 2013-05-07T14:39:00.440 回答