MyPage MyPage MyPage

Razor page property gets empty on handler call

1.1k Views Asked by At

I am using ASP.NET Core and have the following MyPage.cshtml:

@page
@model MyServer.Pages.MyPageModel
@{
    ViewData["Title"] = "MyPage";
}

<h1>MyPage</h1>

@foreach (var sub in Model.Items)
{
    <div>
        <input type="checkbox" id="isSelected" checked="@sub.Value" />
        <label for="isSelected"><strong>@sub.Key</strong></label>
    </div>
}

<a asp-page-handler="Save">Save</a>

And the following MyPage.cshtml.cs:

using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace MyServer.Pages
{
    public class MyPageModel : PageModel
    {
        public Dictionary<string, bool> Items = new Dictionary<string, bool>();
        public void OnGet()
        {
            Items.Add("Item 1", true);
            Items.Add("Item 2", false);
            Items.Add("Item 3", false);
            Items.Add("Item 4", false);
            Items.Add("Item 5", true);
        }

        public void OnGetSave()
        {
            Console.WriteLine("Save button clicked!!");
        }
    }
}

My goal is to trigger the Save() method when the Save element is clicked. But currently it "clears out" the other data on the page:

How do I create a button element to trigger a Save() method to save the state of my data?

1

There are 1 best solutions below

0
Fei Han On

My goal is to trigger the Save() method when the Save element is clicked. But currently it "clears out" the other data on the page

As @MikeBrind mentioned, please put them in a form and specify name attribute for your inputs, like below.

<form method="post">
    @foreach (var sub in Model.Items)
    {
        <div>
            <input type="checkbox" id="isSelected" checked="@sub.Value" name="@sub.Key" />
            <label for="isSelected"><strong>@sub.Key</strong></label>
        </div>
    }

    <button asp-page-handler="Save">Save</button>
</form>

Then you can access selected items from Request.Form collection and use RedirectToPage method(s) to redirect to current page or a specified page, like below.

public IActionResult OnPostSave()
{
    var fb = Request.Form;

    var selected_items = string.Join(",", fb.Keys.ToList().Take(fb.Keys.Count - 1));

    //code logic to save selected items

    Console.WriteLine("Save button clicked!!");


    return RedirectToPage();
}