开发者

Binding a model without controller/http.context

开发者 https://www.devze.com 2022-12-18 09:14 出处:网络
I have a model called \"Channel\" which has a bunch of string properties. I fetch data from my data source which returns a hash table. The Keys of this table match the property names of my model.

I have a model called "Channel" which has a bunch of string properties.

I fetch data from my data source which returns a hash table. The Keys of this table match the property names of my model.

How can I auto-bind the hash table to the Channel model?

The binders from ASP.NET MVC seem to do this but you need to use it in a controller with context. I don't want to pass context into my repository to ma开发者_StackOverflowke it work when fetching data. (although I guess I can if needed)


The method itself is so trivial that you just can't expect "existing" solution for it:

public static T Bind<T>(IDictionary<string, string> hash, T channel)
{
   foreach (var item in hash)
   {
        var prop = typeof(T).GetProperty(item.Key);
        prop.SetValue(channel, Convert.ChangeType(item.Value, prop.PropertyType), new object[0]);
   }
}

That's everything you need. Now you can use this method standalone without any controller, or write a model binder that uses it.

There can be more work with nested properties (you didn't say you need that) but it's 5 more minutes to write using recursion.

0

精彩评论

暂无评论...
验证码 换一张
取 消