Is it possible to use @model in _LoginPartial.csht

2019-04-17 01:37发布

问题:

I need to get some data from my DB from _LoginPartial.cshtml. Is it possible to use @model in _LoginPartial.cshtml? Or how is it done? Just by @using WebApp.Services and then directly retrieve the data from the service? Or it there a more elegant way doing this?

I tried to do it with @model but didn't work because the @model in _LoginPartial.cshtml got overridden by another @model. _LoginPartial.cshtml is "injected" into every page/view.

Views/Shared/_LoginPartial.cshtml

@model WebApp.ViewModels.LoginPartialViewModel
@Html.ActionLink("" + User.Identity.Name + " (" + Model.Email + ")", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })

ViewModels/ManageViewModels.cs

public class LoginPartialViewModel
{
    public string Email = new UserService().ReadCurrent().Email;
}

And the Views/Shared/_LoginPartial.cshtml is used in Views/Shared/_Layout.cshtml like this:

@Html.Partial("_LoginPartial")

Could this be done with @model or would i have to do some nasty thing in Views/Shared/_LoginPartial.cshtml like this:

@using WebApp.Services
var userService = new UserService();
var email = userService.Read(User.Identity.GetUserId()).Email;
@Html.ActionLink("" + User.Identity.Name + " (" + email + ")", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })

回答1:

Every page that uses @Html.Partial("_LoginPartial") needs to do one of two things.

  1. Pass a LoginPartialViewModel object into @Html.Partial("_LoginPartial") as the model e.g. @Html.Partial("_LoginPartial", loginModel)
  2. The model of the view that calls _LoginPartial needs to inherit from LoginPartialViewModel

Using @Html.Partial("_LoginPartial") without the model override causes the partial view to inherit the view context of the parent view. So _LoginPartial wants to inherit whatever model type the calling view uses.



回答2:

You can pass model object as a second parameter to @Html.Partial invocation. But if this partial is used at every page, I suggest to move it to layout.