Ognjen
Ognjen

Reputation: 1195

partial views in ASP.NET MVC

How create View page which is composed of three partial view pages? I am using ASP.NET MVC

    //
    // GET: /Partial/

    public ActionResult View1()
    {
        var upit = from i in proba.name
                   select i;
        return PartialView("upit",proba.name);
    }

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

<h2>Index</h2>
<div><%Html.RenderPartial("View1",proba.name); %></div>
</asp:Content>

Why this code return error: Object reference not set to an instance of an object.

Upvotes: 0

Views: 13869

Answers (2)

tvanfosson
tvanfosson

Reputation: 532745

I think you want to use RenderAction, not RenderPartial. View1 is an action, not a view. It returns the partial view, upit. Note that this requires MVC2 (or MVC1 + futures). You also probably want to decorate the action with the ChildActionOnlyAttribute unless you intend to call it from AJAX as well.

[ChildActionOnly]
public ActionResult View1()
{
    var upit = from i in proba.name
               select i;
    return PartialView("upit",proba.name);
}


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

<h2>Index</h2>
<div><%= Html.Action("View1"); %></div>
</asp:Content>

The reason you are getting the specific error is that the proba variable isn't defined in the view, nor does it need to be. In your case, the action determines the model being passed to the partial view so there's no need for any data to be passed. You could only pass it via query parameters anyway when rendering an action.

Upvotes: 4

James
James

Reputation: 82136

Inside your view page you would want to make use of the RenderPartial method.

Example

Say I had 3 partial views called "View1", "View2" and "View3". If I wanted to render all 3 of these views to make up the content of my view then I would do something like:

<div id="section1">
<% Html.RenderPartial("View1", Model.Table1) %>
</div>
<div id="section2">
<% Html.RenderPartial("View2", Model.Table2) %>
</div>
<div id="section3">
<% Html.RenderPartial("View3", Model.Table3) %>
</div>

I assume you would have a MasterPage which your view derives from in order to take care of the other necessary markup. The above would just be placed inside the Content section of your derived view.

Upvotes: 1

Related Questions