Partial view with @HTML.Action(…)

2019-07-21 08:10发布

问题:

I have a strongly typed partial view that should show the name of an account that a user is logged into:


@model MyNamespace.Models.AccountNameViewModel

@if (Request.IsAuthenticated)
{
    @Html.Action("AccountName", "AccountNameController", Model)
    Logged in to @Model.AccountName
}

I have a controller:

public class AccountNameController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [ChildActionOnly]
    public ActionResult AccountName(AccountNameViewModel model)
    {
        ... Do somthing with the repository to populate the model
        return PartialView(model);

    }
}

What I want to do is add a shared partial view that displays the name of an account that a user is logged into. What I get is the following error:

The controller for path '/ParentViewPath/' was not found or does not implement IController.

Am I at least heading in the right direction?

回答1:

You have to remove the controller part in your call

 @Html.Action("AccountName", "AccountName", Model)

To render a partial view you can also call

 @Html.Partial("AccountName", "AccountName", Model)