Where to put url parsing logic in asp.net mvc?
Let's say I have a ColorsController
and a Colors/Index.cshtml
View for that controller.
I want to make the user able to type an url of the form
Colors/Index/<coma separated list of colors>
and then have the string "abc" be printed for each color that the user passed in, in that same color. An example of an URL would be
Colors/Index/red,white,green,yellow
Now, I've defined the routing the following way:
routes.MapRoute(
"Default",
"{controller}/{action}/{color}",
new { controller = "Colors", action = "Index", color = "black" }
and here is the controller's code:
public ActionResult Index(string colorsParams) {
string[] colors = colorsParams.Split(',');
return View(); //currently does not use colors
}
My question is now on how to go from here on. Should I pass the colorsParams directly to the view and have it parse the info there? Should I do that kind of logic in the model? Right here in the Index() method? This kind of "parsing" logic doesn't seem to be suitable for the model, I'd 开发者_如何学运维say. On the other hand I'd risk saying the view is not the right place, too. How to do this?
Thanks
Controller seem to be acceptable, but if you are going to use it on large scale, consider making custom binder. Passing parsed values to view should be done with model. You can also use ViewBag or ViewData, but using that decreases code maintenability.
You are right that the view is not the right place to put your parsing logic. However, I don't really think that performing the parsing should be done in the Model either, as the Model is really for data and persistence, so if you're not going to save the user's string of colors then there's no need for it to be there.
That leaves the controller, which is probably where it should be. I would just create an array and add it to the ViewData
collection; you can do all of the presentation in your view.
精彩评论