razor in asp.net (c# + html) retrieve value from checkbox

I have a simple view with a checkbox at the bottom:

   @model Application.Areas.Cms.Models.ProduktBeispielViewModel
    @{
        ViewBag.PopupHeadline = "Produktbeispiele";
        ViewBag.PopupSubHeadline = Model.Item != null ? Model.Item.NameInCurrentLang : "";
        ViewBag.HideLanguageComparison = true;
    }
    
    @section TabMenu
    {
        <ul>
            <li><a href="@Url.Action("Index", "ProduktbeispieleEditor", new { id = Model.Item.Id })" class="Active">Einstellungen</a></li>
            <li><a href="@Url.Action("Image", "ProduktbeispieleEditor", new { id = Model.Item.Id })">Bild</a></li>
        </ul>
    }
    
    
    
    
    <form action="@Url.Action("SaveIndex")" method="POST" id="idForm">
        @Html.HiddenFor(m => m.AutoCloseWindow)
        @Html.HiddenFor(m => m.Item.Id)

<checkbox/>

</form>

I have this Index:

public ActionResult Index(int id = 0, int categoryId = 0, bool autoclosewindow=false,bool refreshOpener=false)
{
    var model = LoadModel(id, categoryId);
    model.AutoCloseWindow = autoclosewindow;
    model.RefreshSequenceInOverview = refreshOpener;
    

    foreach (var lang in new LanguageManager().GetItems())
    {
        ...
    }


    return View(model);
}

And ofc I have my model containing the data properties.

I can already display values bound inside my model in my view but I cannot seem to go the way back, meaning if the user checks the checkbox, how do I retrieve that is has been checked?
(Same would go for an editor or entry field)

How can I access the data from my checkbox?

EDIT:

I already have a form of which the checkbox is a child:

<form action="@Url.Action("SaveIndex")" method="POST" id="idForm">
    @Html.HiddenFor(m => m.AutoCloseWindow)
    @Html.HiddenFor(m => m.Item.Id)
    @Html.CheckBoxFor(m => m.Test2)

But when I set a stoppoint at the corresponding function:

    public ActionResult SaveIndex(Product item, List<GeneralLanguageEntry> languages, bool autoclosewindow = false)
    {
...
        return RedirectToAction("Index", new { autoclosewindow = autoclosewindow, refreshOpener = true, id = productFromDb.Id });
    }

The model is not returned here… So i cannot see my altered checkbox

>Solution :

You need to use a rendered control from the html helper rather than just putting a checkbox on the page. This will bind the control to the property in your model.

@Html.CheckBoxFor(m => m.YourBoolValue)

Make sure you have a method that will accept your post data when the form is submitted:

[HttpPost]
public ActionResult SaveIndex(Product item)
...

Leave a Reply