How to reuse form and actions

Asked by At

I'm building a subscription service. Members log in by entering their cellphone number. If there's a match, we send an SMS with a code that they insert on the page, and if that's OK, they're logged in.

Now, we wan't to reuse that when users (not necessarily logged in members) are making subscriptions on other products. So when they've selected a product we wan't them to enter cellphone and SMS-code to proceed.

My question is how I can reuse that without duplicating it?

Right now it's located at /account/login (index.cshtml, index.cshtml.cs) and the new part will probably be on /subscription/start (index.cshtml, index.cshtml.cs).

I know that I can use a Partial View or View Component, but that's only for the view. How can I do so that I don't need to have the actions in both index.cshtml.cs's?

My current form:

@model Models.SMSVerification

<div class="grid space-around">
    <div class="griditem no-padding col-6 col-md-9 col-sm-12">
        <form method="post">
            <div class="form-container">
                @if (Model?.Cellphone == null)
                {
                    <div class="form-group modern">Enter your cellphone number.</div>
                    <div class="form-group modern">
                        <label asp-for="Cellphone"></label>
                        <input asp-for="Cellphone" class="input" />
                        <span asp-validation-for="Cellphone"></span>
                    </div>
                    <div class="form-group buttons">
                        <button type="submit" asp-page-handler="SendSMS" class="btn secondary">Send SMS</button>
                    </div>
                }
                else
                {
                    <div class="form-group modern">Enter the code you received on SMS.</div>
                    <div class="form-group modern">
                        <label asp-for="SMSCode"></label>
                        <input asp-for="SMSCode" value="@Model.SMSCode" class="input" />
                        <span asp-validation-for="SMSCode"></span>
                    </div>
                    <div class="form-group buttons">
                        <button type="submit" asp-page-handler="Verify" class="btn secondary">Login</button>
                        <button type="submit" asp-page-handler="SendSMS" class="btn secondary clean">Send again</button>
                    </div>
                    <input asp-for="Cellphone" type="text" />
                    <input asp-for="Verification" type="text" value="@Model.Verification" />
                }
            </div>
        </form>
    </div>
</div>

1 Answers

0
Elvis Jr On

you can use view components, it's not only for the view, view component has a class where you can write the logic you want and call it any where. see the doc here https://docs.microsoft.com/en-us/aspnet/core/mvc/views/view-components?view=aspnetcore-2.2