As I look at this, this controller action screams for the result of a user action:
public class MyActionResult : ActionResult { public object Model { get; private set; } public MyActionResult(object model) { if (model == null) { throw new ArgumentNullException("Haven't you heard of view models???"); } Model = model; } public override void ExecuteResult(ControllerContext context) { // TODO: You could also use the context.HttpContext.Request.ContentType // instead of this type route parameter var typeValue = context.Controller.ValueProvider.GetValue("type"); var type = typeValue != null ? typeValue.AttemptedValue : null; if (type == null) { throw new ArgumentNullException("Please specify a type"); } var response = context.HttpContext.Response; if (string.Equals("json", type, StringComparison.OrdinalIgnoreCase)) { var serializer = new JavaScriptSerializer(); response.ContentType = "text/json"; response.Write(serializer.Serialize(Model)); } else if (string.Equals("xml", type, StringComparison.OrdinalIgnoreCase)) { var serializer = new XmlSerializer(Model.GetType()); response.ContentType = "text/xml"; serializer.Serialize(response.Output, Model); } else if (string.Equals("csv", type, StringComparison.OrdinalIgnoreCase)) { // TODO: } else { throw new NotImplementedException( string.Format( "Sorry but \"{0}\" is not a supported. Try again later", type ) ); } } }
and then:
public ActionResult Generate(string parameters) { MyViewModel model = _repository.GetMeTheModel(parameters); return new MyActionResult(model); }
The controller does not have to worry about how to serialize the data. This is not his responsibility. The controller should not do plumbing like this. He should focus on selecting domain models, matching them to view models, and transferring these viewing models to view results.
source share