skip to Main Content

I am using

@Html.CheckBoxFor(model => model.AllowOrder, new { id = "allowOrder"})

Now I want to pass its value (whether checked or unchecked) to the controller. I am using html.BeginForm for posting back the data to controller. Every time I am getting its value as null in action method. Action method has below sample code.

public ActionResult index(bool isChecked)
{
    // code here
}

isChecked property is passed in as null always. Any help please. TIA.

2

Answers


  1. If you don’t want to return to controller whole data model, but only one value then see code below:

    public IActionResult IndexTest()
    {
        var model = new ViewModel() { AllowOrder = true };
        return View(model);
    }
    
    [HttpPost]
    public IActionResult IndexTest(bool isChecked)
    {
        // your code here...
        return View("IndexTest", new ViewModel() { AllowOrder = isChecked} );
    }
    

    Using the onclick() to trace the checkbox state:

    @model ViewModel
    
    <script>
        function onStateChange() {
            var item = document.getElementById('allowOrder');
            var chk = false;
            if (item.checked) {
                chk = true;
            }
            document.getElementById('isChecked').value = chk;
        };
    </script>
    @using (Html.BeginForm())
    {
        @Html.Hidden("isChecked", Model.AllowOrder)
        @Html.CheckBoxFor(r => Model.AllowOrder, new { id = "allowOrder", @onclick = "onStateChange()" })
        <input id="Button" type="submit" value="Save" />
    }
    
    Login or Signup to reply.
  2. View:

    @model <specifyModelhere>
    @using(Html.BeginForm("index","<YourControllerNameHere>",FormMethod.Post))
       {
            @Html.CheckBoxFor(r => Model.AllowOrder)
            <input id="Button" type="submit" value="Save" />
        }
    

    Controller:

    public ActionResult index(<YourModelNameHere> model)
    {
        var ischecked = model.AllowOrder;
        // code here
    }
    

    This way when you submit the form, the entire model will be posted back and you can receive it in the controller method

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search