ASP.Net MVC Passing multiple parameters to a view

Nicholas Murray picture Nicholas Murray · Feb 4, 2010 · Viewed 42.1k times · Source

In ASP.Net MVC I would like to render a different partial view depending on the renderview query string parameter.

Therefore providing the facility for the user to choose to view products by thumbnail or by details.

I have access to the chosen parameter in the controller but I do not know how to or, if I should be passing this to the view along with the products list so the view can implement the logic for deciding which partial view to display?

public ActionResult Products(string id, int? renderview)
{
    var products = productRepository.GetProducts(id).ToList();
    return View("Products", products);
}



<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MLBWebRole.Models.Product>>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Products
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<h2>Products</h2>

<p>This is the Products page</p>

<p><a href="?renderview=0">thumbnails</a>&nbsp;<a href="?renderview=1">details</a></p>


 <% if (renderview == 1)
     {%>
    <% Html.RenderPartial("ProductsDetailList"); %>
<% }
else
 { %>
<% Html.RenderPartial("ProductsThumbnailList"); %> 
  <% } %>

</asp:Content>

Answer

Nitin Midha picture Nitin Midha · Feb 4, 2010

Your View Should be something like:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Models.MyModel>" %>

Then in MyModel

Expose Property:

public bool RenderDetailView {get;set;}

In your controller action:

public ActionResult Products(string id, int? renderview)
{
    var products = productRepository.GetProducts(id).ToList();
    return View("Products", new MyModel {RenderDetailView = renderview.HasValue});
}

Then in your view, make check like:

<% if (Model.RenderDetailView)

Ideally, all the properties or parameters or data which a View needs in order to present itself should be part of Model.

I hope it helps.