简体   繁体   中英

How do you bind a checkbox in .net core razor pages?

How do you bind a checkbox in .net core razor pages? I'm currently having problems where the checkbox value isn't coming back when I submit the form (using post method).

Below is my code.

domain classes:

public class Restaurant
{
    public int Id { get; set; }
    [Required, StringLength(80)]
    public string Name { get; set; }
    public Meals MealsServed { get; set; }

}
public class Meals
{
    public int Id { get; set; }
    public bool Breakfast { get; set; }
    public bool Lunch { get; set; }
    public bool Dinner { get; set; }
}

from page model:

    [BindProperty]
    public Restaurant Restaurant{ get; set; }
    public EditModel(IRestaurantData restaurantData, IHtmlHelper htmlHelper)
    {
        this.restaurantData = restaurantData;
        this.htmlHelper = htmlHelper;
    }
    public IActionResult OnGet(int? restaurantId)
    {

            Restaurant = restaurantData.GetById(restaurantId.Value);
            Restaurant.MealsServed.Breakfast = true;
            return Page();
    }

    public IActionResult OnPost()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }
        restaurantData.Update(Restaurant);
        restaurantData.Commit();
        TempData["Message"] = "Restaurant Saved";
        return RedirectToPage("./Detail", new { restaurantId = Restaurant.Id });

    }

from razor page:

<form method="post">
<input type="hidden" asp-for="Restaurant.Id" />
<div class="form-group">
    <label asp-for="Restaurant.Name"></label>
    <input asp-for="Restaurant.Name" class="form-control" />
    <span class="text-danger" asp-validation-for="Restaurant.Name"></span>
</div>

<div class="form-group">
    <input asp-for="Restaurant.MealsServed.Lunch" />
    <label asp-for="Restaurant.MealsServed.Lunch"> </label>
</div>

<button type="submit" class="btn btn-primary">Save</button>
</form>

So, I figured out the problem. Everything was correct that I presented above. After checking the checkbox for Lunch and saving the item, and then viewing the Restaurant item again, it would come back unchecked.

The issue was with the depth of the data that I was pulling from the database. It was only pulling the top level of data. So, I had to change GetById method from:

public Restaurant GetById(int id)
{
   return db.Restaurants.Find(id);
}

to:

public Restaurant GetById(int id)
{
  return db.Restaurants.Where(r => r.Id == id).Include(r => r.MealsServed).FirstOrDefault();            
}

explicitly telling it to pull the data for the object in the MealsServed property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM