1

I am trying to print the name of the user who executes my web app. It is written in MVC-Razor.

From the initial View, I would to execute the controller below:

    [Authorize]
    public ActionResult Check()
    {
        var check = new CheckAD();
        var user = new User {Name = check.CheckSecurityWithAD()};
        if (!string.IsNullOrEmpty(user.Name))
        {
            return View("Checked", user);
        }
        
        var errors = new ErrorsModel()
        {
            Messages = new List<string>(){"You don't have permission"}
        };
        
        return View("Error", errors);
    }

This controller returns another view if the user is correctly authenticated:

   @model UsersActivationWeb.Models.User

   @{
        ViewBag.Title = "Checked";
    }

   @{ <p> Logged come @Model.Name </p>};

How can I print the second view (I think it's a partial view) in the first one using the controller?

Thanks

1
  • In the first view, you need to use partial like @html.Partial("ViewName") Commented Sep 4, 2020 at 11:52

1 Answer 1

1

Sounds to me like you need an Html.Action. This will run the controller code and display the view contents that are produced where you place the call.

Most likely you will need this overload, Html.Action(string actionName, string controllerName).

Assuming the controller is called CheckController. In your initial view call it like this

@Html.Action("Check","Check")

Since you don't want people navigating to the Check view you should give it a ChildActionOnly attribute so it looks like this

[Authorize]
[ChildActionOnly]
public ActionResult Check()
{
   //rest of code
}

Finally you almost certainly don't want the layout contents to appear with the Checked view so change your Checked view to this

@model UsersActivationWeb.Models.User

@{
    Layout = null;
 }

@{ <p> Logged come @Model.Name </p>};

Since you are doing authorization logic in the Check action you might not need the Authorize attribute. I say that because with it a user not logged in will not get the error or their name. Maybe you want this though, I'd need to know more about your code to say for sure.

This way you will either get the name of the user or the errors as required.

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

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.