2013-05-07 2 views
0

Я пытаюсь сделать конверсию с помощью Google API. Тем не менее, я получаю, и индекс был ошибкой вне диапазона, и сбор формы не собирает данные, как я хочу (сумма, currencyFrom, currencyTo). Что я делаю не так?MVC Получить и отправить данные - Конвертация денег

Обменный курс управления:

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

Ваш вход считается сложным объектом. Лучше всего использовать для этого модель просмотра, так что вы также можете воспользоваться связующим устройством модели.

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

Могу ли я использовать эту модель тоже (который я retreving имена различные валюты из базы данных): @model IEnumerable rikket

+0

Право Я забыл добавить метод GET, см. мой обновленный ответ –

+0

Спасибо для вашей помощи! Я попробую это завтра и дам знать. – rikket

Смежные вопросы