Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model is null in partial view

I'm trying to add a partial view inside a layout page.

Model

public class SummaryPanelModel
    {
        public int TotalDesignDocs { get; set; }
        public int TotalVendorDocs { get; set; }
        public int TotalBusinessDocs { get; set; }
        public int TotalManagementDocs { get; set; }
    }

SummaryPanel_Partial Partial View Controller:

 public ActionResult SummaryPanel_Partial()
        {
            rep = new SummaryRepository();
            SummaryPanelModel model = new SummaryPanelModel();
            model = rep.ReadsummaryPanel();//read from database
            return View(model);
        }

Layout Page

<!DOCTYPE html>
<html lang="en">
@{
    Layout = null;
}

 @Html.Partial("SummaryPanel_Partial")

SummaryPanel_Partial Partial View:

@model Doc.Web.Models.SummaryPanel.SummaryPanelModel

<div id="pnlBar">
    @Html.Label(Model.TotalDesignDocs.ToString())
<div/>

despite the fact that I have passed the model in controller action, the model is always null in the partial view.

like image 827
chamara Avatar asked Mar 20 '23 04:03

chamara


1 Answers

@Html.Partial("SummaryPanel_Partial")

Calling a partial in this way will not call the controller+action. Instead, it simply finds the view SummaryPanel_Partial and renders it. Since you provide no model at this point, the model is null.

Instead, call Html.Action, which will call the controller+action.

@Html.Action("SummaryPanel_Partial", "Controller")

And change your action:

public ActionResult SummaryPanel_Partial()
{
    // ...
    return PartialView(model);
}
like image 167
Rowan Freeman Avatar answered Mar 29 '23 08:03

Rowan Freeman