C
C#10mo ago
palapapa

❔ Is it a good idea to use a "processed model" in addition to the model bound by ASP.NET itself?

First of all, I wanted to do this because I wanted to avoid writing a custom model binder. Let's say I want to get a string from the query string in a request, and convert that string into DotNet.Glob(which requires calling Glob.Parse(string)). If I don't want to convert it manually in the action method, the other option is to write a custom model binder, but I don't want to do that because it seems like a hassel and the documentation isn't good about how to properly implement one. So I came up with the following constuct:
interface IProcessedModel<Model>
{
public static abstract ProcessFrom(Model model);
}

class MyModel
{
public string Path { get; set; }
}

class MyProcessedModel : IProcessedModel<MyModel>
{
public Glob Glob { get; private set; }
public static ProcessFrom(MyModel myModel)
{
Glob = Glob.Parse(myModel.Path);
}
}
interface IProcessedModel<Model>
{
public static abstract ProcessFrom(Model model);
}

class MyModel
{
public string Path { get; set; }
}

class MyProcessedModel : IProcessedModel<MyModel>
{
public Glob Glob { get; private set; }
public static ProcessFrom(MyModel myModel)
{
Glob = Glob.Parse(myModel.Path);
}
}
Then in my action method, I can just do:
MyProcessedModel processedModel = MyProcessedModel.ProcessFrom(model); // model is the original model bound by ASP.NET
MyProcessedModel processedModel = MyProcessedModel.ProcessFrom(model); // model is the original model bound by ASP.NET
This seems to work fine. Is this a good idea instead of a custom model binder?
2 Replies
Tvde1
Tvde110mo ago
I'd recommend that whatever you pass to your business logic, not to have ASP.net code inside it it's unlikely that you're going to switch to e.g. RPC or an event queue handler etc, but it's good practice
Accord
Accord10mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.