2012-02-29 46 views
0

我有一個csv文件列表可以從下拉列表中進行選擇。每個csv的數據都不相同。我正在使用csv文件,並希望使用相同的webgrid顯示數據。我是否會將動態對象傳遞給webgrid,以便webgrid可以顯示所有csv數據的列和值?如果對同一個webgrid控件的不同對象

回答

0

是的,你可以使用動態視圖模式:

public class MyViewModel 
{ 
    public string SelectedCsv { get; set; } 
    public IEnumerable<SelectListItem> AvailableCsv { 
     get 
     { 
      return new[] 
      { 
       new SelectListItem { Value = "foo.csv", Text = "foo.csv" }, 
       new SelectListItem { Value = "bar.csv", Text = "bar.csv" }, 
       new SelectListItem { Value = "baz.csv", Text = "baz.csv" }, 
      }; 
     } 
    } 

    public IEnumerable<object> Data { get; set; } 
} 

,然後有一個控制器:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     var model = new MyViewModel 
     { 
      Data = GetData("foo.csv"), 
     }; 
     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Index(MyViewModel model) 
    { 
     model.Data = GetData(model.SelectedCsv); 
     return View(model); 
    } 

    // TODO: move this method away in a repository and 
    // do the actual parsing of the CSV file 
    private IEnumerable<object> GetData(string csv) 
    { 
     if (csv == "foo.csv") 
     { 
      return new[] 
      { 
       new { col1 = "value1", col2 = "value2" }, 
       new { col1 = "value1", col2 = "value2" }, 
      }; 
     } 
     else if (csv == "bar.csv") 
     { 
      return new[] 
      { 
       new { col1 = "bar value1", col2 = "bar value2", col3 = "bar value3" }, 
      }; 
     } 
     else if (csv == "baz.csv") 
     { 
      return new[] 
      { 
       new { col1 = "baz value1" }, 
       new { col1 = "baz value2" }, 
       new { col1 = "baz value3" }, 
      }; 
     } 

     throw new NotImplementedException(); 
    } 
} 

,並在視圖:

@model MyViewModel 

@using (Html.BeginForm()) 
{ 
    @Html.DropDownListFor(x => x.SelectedCsv, Model.AvailableCsv) 
    <button type="submit">OK</button> 
} 

@{ 
    var grid = new WebGrid(Model.Data); 
} 

@grid.GetHtml() 

至於對CSV文件的解析而言,如果有一件事情你應該從來沒有做,那將是roll your own CSV parser

相關問題