Pregunta

Given a web application that receives a text file via upload from the client, parses it using various rules, and outputs a view based on some rules, where would the various stages of this process be allocated in a MVC structured project?

Initially, I was going to send the uploaded file to a helper method (separate from any of my models, views and controllers) which would parse and generate the output and push the output to the database using a model; I would then render a view from the controller with the output.

I suspect the parsing and generation of the output based on rules is business logic? In this case should I be putting the code under models or is a helper ok? Thus far, I have only been using my model to access the database and store the classes for my objects (User, TextDocument, etc.); if in face that my file parsing etc. should go in the model, how is that usually structured? Do I just add a FileParser class to the model or?

¿Fue útil?

Solución

You are right to think about separating things out, and it certainly seems right to split the parsing of content out from the model.

I have used helpers sometimes to get the job done. If you are looking to make it more testable and keep you models clean though (esp the case if the models are Entity Framework models), then an approach similar to that shown below might be of use.

/// <summary>
/// Interface for file handling
/// </summary>
public interface IFileParser
{
  void Parse();
}




/// <summary>
/// An interface for the model you wish to work on
/// Will allow DI and Mocking in Unit Tests
/// </summary>
public interface IMyModel
{
  string Content { get; set; }
}


/// <summary>
/// The model that has the content you are going to work with
/// </summary>
public class MyModel : IMyModel
{
  string Content { get; set; }

  // other properties
}



/// <summary>
/// The class to handle the model.
/// </summary>
public class FileHandler : IFileParser
{
  private IMyModel _model;

  public FileHandler(IMyModel model)
  {
    _model = model;
  }

  public void Parse()
  {
    string contentToHandle = _model.Content;
    //Do stuff here to ensure all is good.
    //NOTE: you could change the interface to return an ID to work with
  }
}

You could then handle the parsing like so:

FileHandler handler = new FileHandler(thisModel);
handler.Parse();

This could be overkill though. Depends on what you are working on :)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top