0

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.

2
  • So what is the question ? Commented Jun 4, 2014 at 7:15
  • Edited the question hoping to clatrify. Commented Jun 4, 2014 at 7:22

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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")
}

1 Comment

Thank you! I´ll defenitley try out this one too!
0
@Html.Partial("ViewName")
@{ Html.RenderPartial("ViewName"); }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.