MVC comparing url value with item in model

P

Phil

I am showing a list of items by category. Each item may belong to more than
one category, so the Model features a CategoryList collection for each item.
The CategoryList collection contains a CategoryID (int) and a CategoryName
(string). At the moment, I am iterating the Category collection to find an
item that matches part of the page URL with the CategoryID to write the
category name to the page. It works, but looks and feels horrible. I'm
doing this in the View:

--------------------------------------------------
Items in the
<%
foreach(var item in Model.First().CategoryList)
{
if
(Request.Url.ToString().Substring(Request.Url.ToString().LastIndexOf("/")+1,((Request.Url.ToString().Length-1)-
Request.Url.ToString().LastIndexOf("/"))) != "")
{
if (item.CategoryID ==
Convert.ToInt32(Request.Url.ToString().Substring(Request.Url.ToString().LastIndexOf("/")+1,((Request.Url.ToString().Length-1)-
Request.Url.ToString().LastIndexOf("/")))))
Response.Write(item.CategoryName);
}
} %>

Category
--------------------------------------------------

There must be a better way to do this. Can anyone point me in the right
direction?

Thanks
 
C

Cowboy \(Gregory A. Beamer\)

If it were me, I would "denomalize" the model a bit to include the
information you desire and you will then have an element that can be bound
without running through a secondary table.

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

Blog:
http://feeds.feedburner.com/GregoryBeamer

*********************************************
| Think outside the box |
*********************************************
 
P

Phil

So you are suggesting adding a property to the object which will hold the
name of the selected category? I guess that would certainly result in a
cleaner View (in terms of code).

Thank you.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top