[RESOLVED]Want to Add a partial view but I get an error

I got this controller for the partial:

        public PartialViewResult BlogTitle(Blog model)
        {

            return PartialView(db.Blog.ToList());
        }

This controller is related to the page I want to have the partial View in:

        public ActionResult Index()
        {
            return View();
        }

and this is the partialView:

@model IEnumerable<CMS.Models.Blog>

@{
    int x = 0;
}
<div class="sub1-1st-section">
    <section class="sub-section">
        <h3>
            Lately
        </h3>
        @foreach (var item in Model)
        {

            @Html.ActionLink(@item.Subject, "Details", "Blog", new { id = item.Id })
            <hr />
            x++;
            if (x > 5)
            {
                break;
            }
        }
    </section>
</div>

I got problem in this part:

@Html.Partial("~/Views/Blog/BlogTitles.cshtml")

what can I do?

Please ALWAYS be explicit and post the error message (or the closest English translation you can) or describe the bad behavior you see.

It seems the controller shouldn’t compile, BlogTitles doesn’t match BlogTitle or nothing is passed but as you don’t have told anything about the error or bad behavior you SEE, I’m unable to confirm or reject any of those first thoughts (and
it could be still some other issue I didn’t saw or for which you didn’t show something we could use).

So in short if you ask others to solve a problem, please do tell what is the problem you have !!

One thing I could notice from your code is the action name and partial view are not matching, if you are expecting the data from the controller.

You can pass the data from your view to the controller as @html.partial(partialview name, in your case ienumerable list)

@Html.Partial("~/Views/Blog/BlogTitles.cshtml")

BlogTitle(Blog model)

I get this error: 

Object reference not set to an instance of an object.

and Thanks to you I corrected the names. but I still get the Error.

Do you have the data in the view?

I could see the data is missing while rendering the partial view.

This data has to be passed from the view while rendering the partial view as @html.partial(partial view name, list)

@model IEnumerable<CMS.Models.Blog>

I changed the View Part to this:

@var db = new ApplicationDbContext();

@Html.Partial("BlogTitle", db.Blog.ToList())

and it’s working now… Thanke you all.

And where does it happen? How do you initialize the db variable which is used in your controller? Could it be this variable which is null?

Leave a Reply