Form in Layout: Razor Pages

2020-07-31 04:47发布

问题:

I have a select in a form in the Layout of my web app that needs to be accessible from every page. The form sets a session variable that is required to load data on every page.

<form asp-page-handler="CustomerChange" method="post" class="navbar-form navbar-left">
    <select name="Customer" id="Customer" class="form-control" onchange="this.form.submit()">
        <option value="">Select Customer</option>
        <option value="Vand">Vandalay</option>
        <option value="Kram">Kramerica</option>
    </select>
</form>

I know I can make a base PageModel and inherit from that on every page in order to respond to a OnPost e.g.

public abstract class BaseSecurePageModel : PageModel
{
    [BindProperty]
    public string Customer { get; set; }
    public virtual void OnPostCustomerChange()
    {
        HttpContext.Session.SetString("Customer", Customer);
    }
}

but this doesn't lend itself to having the model binded to the form and also requires that I remember to inherit from the base class in every page. Is there a correct way to handle forms that need to be available everywhere?

回答1:

Try using a Controller instead and have your CustomerChange ActionResult specify a [Route()]. I use a Controller for most of my Layout items such as shopping carts, localization etc... in razor pages and works pretty well.

// Updated answer based on feedback from Steven B.

Below is an example of the localization I spoke about above. The form triggers a post against the SetLanguage method in the BaseController.cs

In the _Layout.cshtml file I have, in this instance, a partial view:

@Html.Partial("_SetLanguagePartial") // Used prior to .net core 2.1

<partial name="_SetLanguagePartial" /> // Used for .net core 2.1+

The html inside this _SetLanguagePartial.cshtml contains a form with the corresponding asp-controller and asp-action

 <form id="selectLanguage" asp-controller="Base" asp-action="SetLanguage" asp-route-returnUrl="@returnUrl" method="post" class="form-horizontal" role="form">
    <ul class="list-inline">
      @foreach (var culture in cultureItems)
      {
         var countryIcon = "usa.png";
         <li>
             <button type="submit" class="btn btn-sm btn-link" name="culture" title="@culture.Text" value="@culture.Value">

               @switch (culture.Text)
               {
                  case "Japanese" :
                       countryIcon = "japan.png";
                       break;
                   case "Spanish" :
                       countryIcon = "spain.png";
                       break;
                   default:
                       break;
                }

                 <img src="@Configuration["BlobStorage:StorageUrl"]/images/@countryIcon" alt="@culture.Text"/>
               </button>
          </li>
       }
   </ul>
</form>

BaseController.cs

[Route("[controller]/[action]")]
        public class BaseController : Controller
        {
            [HttpGet]
            public IActionResult GetCartViewComponent()
            {
                return ViewComponent("Cart");
            }

            [HttpPost]
            public IActionResult SetLanguage(string culture, string returnUrl)
            {
                Response.Cookies.Append(
                    CookieRequestCultureProvider.DefaultCookieName,
                    CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
                    new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1)}
                );

                return LocalRedirect(returnUrl);
            }
        }