My view is not a strongly typed view and I need to iterate through Request Params in the controller action to determine the values posted.
Is there a better way to iterate through the nameValueCollection AllKeys?
I am currently looping through the Request Params and setting values appropriately.
foreach (var key in Request.Params.AllKeys)开发者_如何转开发
{
if (key.Equals("CustomerId"))
queryObject.CustomerId = Request.Params[key];
else if (key.Equals("OrderId"))
queryObject.OrderId= Request.Params[key];
//and so on
}
I see a considerable amount of repetition in this code. Is there a better way to handle this?
Maybe something like this?
queryObject.CustomerId = Request.Params["CustomerId"];
queryObject.OrderId = Request.Params["OrderId"];
Because the NameValueCollection does not provide a Search method and simply by clarify your code, you could do the following:
foreach (var key in Request.Params.AllKeys)
{
queryObject.CustomerId = key.Equals("CustomerId") ? Request.Params[key] : queryObject.CustomerId;
queryObject.OrderId = key.Equals("OrderId") ? Request.Params[key] : queryObject.OrderId;
//and so on ...
}
Could you not use reflection to getProperties from your query object, then read through them to get the corresponding items from the request.params?
http://www.csharp-examples.net/reflection-property-names/
http://msdn.microsoft.com/en-us/library/kyaxdd3x.aspx
It looks like C# has an equivalent of a Java Map
:
Java Map equivalent in C#
If nothing else works, I'd recommend building a Dictionary
of key-value pairs, then reading the values out of the Dictionary
into the class object.
精彩评论