user2915962
user2915962

Reputation: 2711

Method to render partial view

I got a partialView that I would only like to render if the user is logged in. Im thinking something like this:

View:

@Html.ActionLink("Text", "Method", "Controller")



<section id="events">

    @Html.Partial("_CreateNewPost")

</section>

Controller:

    [Authorize]
    public ActionResult Method()
    {

        Code that renders the PartialView
        return View();
    }

This way, I would asume that a user that is not logged in will be sent to the login-page. Thanks!

Edit: So im wondering if its possible to create code in the method that renders the partial view. The way it is now, the partial view gets rendered as soon as the page loads.

Upvotes: 0

Views: 983

Answers (3)

Tobias
Tobias

Reputation: 2840

Sure it's possible. On your controller:

[Authorize]
[ChildActionOnly]
public ActionResult MyPartial()
{
    //Do stuff...
    return PartialView("_partialViewName");
}

and then in your view:

@Html.Action("MyPartial", "ControllerName")

This is useful in cases where you want to return different partial view, depending on some condition, or if you want to pass some data, like a viewmodel, to the View. The ChildActionOnly specifies that this view is only accessible when it's called from another view, so you can't just type /controller/MyPartial in the address bar.

Upvotes: 1

Ufuk Hacıoğulları
Ufuk Hacıoğulları

Reputation: 38468

You can use a child action:

[Authorize]
public ActionResult Method()
{
    return PartialView("_CreateNewPost");
}

Then call it in your view:

@if(Request.IsAuthenticated)
{
    Html.Action("Method","SomeController")
}

Upvotes: 1

Robert P
Robert P

Reputation: 157

@Html.Partial("ViewName")
@{ Html.RenderPartial("ViewName"); }

Upvotes: 0

Related Questions