使用远程CSV并将其转换为MVC中的视图模型

本文关键字:MVC 模型 视图 转换 CSV | 更新日期: 2023-09-27 18:12:19

我在远程服务器上有一个CSV文件,可以通过URL访问,例如:http://mydomain.com/test.csv。它只是一个键/值对的记录。在控制器中,如何使用CSV文件并将其作为模型传递给视图?我对MVC3有点陌生,所以我很感激你的帮助。

下面是我的CSV示例:

key,value
Key1,ValueA
Key2,ValueB
Key3,ValueC
Key4,ValueD

使用远程CSV并将其转换为MVC中的视图模型

我不会从控制器调用它。我会使用接口驱动的开发,将逻辑委托给服务。

快速google会为CSV解析器产生大量结果。所以这只是构造一个HTTP请求,解析CSV,然后将其映射到ViewModel的问题。

那么你的控制器可以是这样的:

    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解析器(或使用您自己的),您的Controller就不需要更改。您可以在整个应用程序中重用此服务。

这似乎是一个很基本的问题。像这样的东西应该让你开始。

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