This is the situation:
I have an ASP.NET MVC 4 application. When I run the application I go to a page and the Index – action on the controller takes a Guid as id – parameter. With that id I get a list of items from a database and put it into a ViewModel. This ViewModel is passed to a View which lists all of the items as an ActionLink (could be changed if necessary). When I click one of the items I want to get a list of other items, based on the id of the selected link, and show this new list right next to the first list.
But this is my question (and where I’ve been stuck for 2 days):
What is the best way to do this? Go to a new page or use a partial view. Because I have been trying a bit of both and clearly I must’ve done some things wrong because none seemed to work. I don’t need any AJAX-stuff or helpers like that, only a correct way to get this done… 🙂
Thanks in advance!
Update: the code that I already have
View
@foreach (var order in Model.Orders)
{
<p>@Html.ActionLink(order.Name,
"OrderItems",
"OrdersController",
new { id = order.Id },
null)
</p>
}
@if (Model.Detail != null)
{
@Html.Partial("_OrderItemsByOrder", Model)
}
Controller
public ActionResult Index(Guid id)
{
var orders = Services.GetOrders(id);
var viewModel = new OrdersViewModel { Orders = orders };
return View(viewModel);
}
public ActionResult OrderItems(Guid id, OrdersViewModel model)
{
var orderItems = Services.GetOrderLines(id);
var viewModel = new OrdersViewModel
{
Orders = model.Orders,
Detail = new OrderDetailViewModel { OrderItems = orderItems }
};
return PartialView(viewModel);
}
There are several ways you could achieve a master/detail page like this, there really is no best way to do this. AJAX may be the most elegant and user friendly, but it’s by no means the “right” answer.
Looking at the code you posted, the simplest thing you could do is have one action method and one view.
The drawback with this rather basic approach is that you’ll have possibly 2 Guids dirtying up your Url and this example doesn’t verify that the orderId is actually owned by the (user?) Id – whatever the first Guid represents. You could handle this with a few lines of code though.
A more elegant way of handling this, if you don’t mind your Url changing, is to stick with the second action method. I would hope you can determine the “owner” of an order detail from the detail itself, or in some way that wouldn’t require you to pass this into the action method. This helps ensure that your view only shows details from the right master.
Your view as listed in your question can largely stay the same. Render the action links that represent all of the orders. Then render the order details if there is one in the model:
If you are rendering the order details on other pages, you’ll want to put your order details in a partial view so you don’t duplicate any of your markup. If it’s only rendered here, then there’s really no reason why you couldn’t have your markup right in this view.