Beginner MVC question - Correct approach to render out a List and details?

Posted by fizzer on Stack Overflow See other posts from Stack Overflow or by fizzer
Published on 2010-05-27T11:30:28Z Indexed on 2010/05/27 12:01 UTC
Read the original article Hit count: 185

Filed under:
|
|

I'm trying to set up a page where I display a list of items and the details of the selected item. I have it working but wonder whether I have followed the correct approach. I'll use customers as an example

I have set the aspx page to inherit from an IEnumerable of Customers. This seems to be the standard approach to display the list of items. For the Details I have added a Customer user control which inherits from customer.

I think i'm on the right track so far but I was a bit confused as to where I should store the id of the customer whose details I intend to display. I wanted to make the id optional in the controller action so that the page could be hit using "/customers" or "customers/1" so I made the arg optional and stored the id in the ViewData like this:

public ActionResult Customers(string id = "0")
    {
        Models.DBContext db = new Models.DBContext();
        var cList = db.Customers.OrderByDescending(c => c.CustomerNumber);
        if (id == "0")
        {
            ViewData["CustomerNumber"] = cList.First().CustomerNumber.ToString();
        }
        else
        {
            ViewData["CustomerNumber"] = id;
        }
        return View("Customers", cList);
    }

I then rendered the User control using RenderPartial in the front end:

<%var CustomerList = from x in Model
                        where x.CustomerNumber == Convert.ToInt32(ViewData["CustomerNumber"])
                 select x;
         Customer c = (Customer)CustomerList.First(); %>
<% Html.RenderPartial("Customer",c); %>

Then I just have an actionLink on each listed item: <%: Html.ActionLink("Select", "Customers", new { id = item.CustomerNumber })%>

It all seems to work but as MVC is new to me I would just be interested in others thoughts on whether this is a good approach?

© Stack Overflow or respective owner

Related posts about c#

Related posts about asp.net-mvc