问题
I'm building a new website and one of the requirements is to have the login form be a modal window. I'm trying to include it in the top navigation bar and it's only being rendered if the user is not logged in.
How can I add this modal window with it's own model inside the top navbar? Are there any alternatives?
If I delete the model and let an empty modal everything works perfectly but when I add it again it doesn't work, because the model of the page (in this case the index page) is a different one then the one from the modal login.
P.S. I'm using Razor Pages and ASP.NET Core 2.2.
回答1:
Partial View
So you make a _LoginPartial.cshtml
file. and let's say you set @model LoginViewModel
Inside this _LoginPartial.cshtml
you have your Login Modal and all the functionality.
Now when you invoke your partial inside an Index
page that has model @model AnotherModel
, you need to pass a new model to the partial like so:
<partial name="_LoginPartial" model='new LoginViewModel()' />
name
is the name of your cshtml
page.
model
is the @model
of the page.
Read More Here
View Components
To be brief if you take this route this is essentially like nesting a little controller inside your page. Allowing you to change scope for your @model
.
Read more about View Components
Update for nested objects
You need to instantiate the object property.
<partial name="_LoginPartial"
model='new LoginViewModel { InputModel = new InputModel() }' />
来源:https://stackoverflow.com/questions/54286289/insert-a-modal-razor-page-in-the-navbar-how-to-do-it