Reputation:
I am developing a web application on Asp.Net Core 2.0 MVC, there is a sign-up modal form that will be used across all pages and not being able to understand how should I do the user model binding since every page will have it's own model.
For example, there is a news page that will use the News model and while on that page, a user will want to either sign-up or sign-in (2 modal forms that are integrated in the main layout).
Below is the form section of the sign-up modal:
<form action="/Account/RegisterAccount" method="post">
@Html.AntiForgeryToken()
<div class="cfield">
<input name="username" type="text" placeholder="Username" />
</div>
<div class="cfield">
<input name="email" type="text" placeholder="E-mail address" />
</div>
<div class="cfield">
<input name="password" type="password" placeholder="Password" />
</div>
<div class="cfield">
<input type="password" placeholder="Confirm Password" />
</div>
<button type="submit">Register</button>
</form>
What I did so far is simply submitted the form data without a model, but I was thinking maybe it would be better to find a way to bind the model so I can also do the model validation.
Also, if someone could give me an advice on what is the best practice to manage the logged in user, would be a very good help.
This is my very first post here, and I am totally new at Core and MVC.
Upvotes: 1
Views: 284
Reputation: 239250
Never, never, never attach a model to a layout. Just don't. The correct approach here is a view component. Create a ViewComponents
directory and add a class file like SignUpViewComponent.cs
to that. In that file, you'll need something like:
public class SignUpViewComponent : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync()
{
// set up your model
return View(model);
}
}
View components support injection, so you can follow the tradition DI pattern of adding a constructor with the params you want to inject and setting private fields on your class with those values. This allows you to easily bring in things like your context, if you need to utilize it to build your model.
Then, create the view Views\Shared\Components\SignUp\Default.cshtml
. In that file you can set the model to the your sign up form model as you want, and then just add your signup form HTML, utilizing that model.
Finally, in your layout, add the following line where you want the signup form to appear:
@await Component.InvokeAsync("SignUp")
For more information on view components, refer to the documentation.
Upvotes: 2