我有一個遠程服務器上的CSV文件是通過URL,例如訪問:http://mydomain.com/test.csv。它只是一個鍵/值對的記錄。在我的控制器中,我將如何使用該CSV文件並將其作爲模型傳遞給視圖?我對MVC3有點新,所以我很感激任何幫助。消費遠程CSV並轉換爲MVC中的視圖模型?
這裏是我的CSV樣本:
key,value
Key1,ValueA
Key2,ValueB
Key3,ValueC
Key4,ValueD
我有一個遠程服務器上的CSV文件是通過URL,例如訪問:http://mydomain.com/test.csv。它只是一個鍵/值對的記錄。在我的控制器中,我將如何使用該CSV文件並將其作爲模型傳遞給視圖?我對MVC3有點新,所以我很感激任何幫助。消費遠程CSV並轉換爲MVC中的視圖模型?
這裏是我的CSV樣本:
key,value
Key1,ValueA
Key2,ValueB
Key3,ValueC
Key4,ValueD
我不會從控制器調用它。我會使用接口驅動開發將該邏輯委託給服務。
A quick google產生大量結果爲CSV解析器。所以它只是一個構建HTTP請求,解析CSV,然後將其映射到一個視圖模型的問題。
所以你的控制器看起來是這樣的:
private ICsvParsingService _csvParsingService; // tip: use DI to inject the concrete in ctor.
[HttpGet]
public ActionResult Csv()
{
var csv = _csvParsingService.Parse("http://mydomain.com/test.csv");
var model = Mapper.Map<SomeCsvType,YourModel>(csv); // AutoMapper. Or you could do L-R.
return View(model);
}
這樣一來,如果你決定使用不同的CSV解析器(或滾你自己),你的控制器不需要改變。你可以在你的應用程序中重新使用這項服務。
+1非常乾淨的解決方案 –
這似乎是這樣一個基本問題。像這樣的東西應該讓你開始。
WebClient client = new WebClient();
string csvContents = client.DownloadString(UrlAsString);
string[] csvLines = csvContents.Split(new string[] {"\n", "\r\n"},
StringSplitOptions.RemoveEmptyEntries);
SomeModel model = new SomeModel()
model.KeyValuePairs = csvLines.Select(x => x.Contains(","))
.Select(x => new KeyValuePair(x.Split(",")[0],
x.Split(",")[1]);
public class SomeModel()
{
public IEnumerable<KeyValuePair> KeyValuePairs { get; set; }
}
public class KeyValuePair()
{
public KeyValuePair() { }
public KeyValuePair(string Key, string Value)
{
this.Key = Key;
this.Value = Value;
}
public string Key { get; set; }
public string Value { get; set; }
}
哪一部分,你需要幫助嗎?下載文件?解析CSV?將它用作模型? – Aliostad
你想在每一個請求解析CSV?你可以考慮緩存策略。 –