Home > Blockchain >  How to pass value of checkbox from Ajax.BeginForm to controller
How to pass value of checkbox from Ajax.BeginForm to controller

Time:12-01

I have the follwoing code below, which uses Ajax.BeginForm() to pass some values to the controller. I have added a checkbox and now trying to send its value (checked or unchecked) into the controller as well (that is passing it into ReceiverFunc). However, I can't figure out how to send the value of the checkbox into ReceiverFunc.

DateViewer.cshtml

 <div >
            @using (Ajax.BeginForm("ReceiverFunc", "View", new AjaxOptions { GenerateTargetId = "wrapper" }))
            {
                <fieldset>
                    <form>
                            <label>Starting date:</label>
                            @Html.JQueryUI().DatepickerFor(model => model.Start, new { @id = "date1" })
                            <script type="text/javascript">
                                saveDate("date1");
                            </script>

                            <label>End date:</label>
                            @Html.JQueryUI().DatepickerFor(model => model.End, new { @id = "date2" })
                            <script type="text/javascript">
                                saveDate("date2");
                            </script>

                            <input type="submit" value="Generate List" />
                            @* TODO - Get this value into the controller as well  *@
                            Checkbox: <input type="checkbox" id="check">
                    </form>
                </fieldset>
            }
 </div>

And here is the controller where I want to receive it. ViewController.cs

 public class ViewController : Controller
{
   DatabaseClass.DatabaseHandler db = new DatabaseClass.DatabaseHandler();
    Models.EventModel myModel = new Models.EventModel();

    [HttpPost]
    public ActionResult ReceiverFunc(Models.EventModel myModel)
    {
       result   = db.TriggerDBFunction(myModel);

        // ....
    }
}

Eventmodels.cs

public class EventModel
{
    public DateTime Start{ get; set; }
    public DateTime End { get; set; }
    public bool CheckValue { get; set; }
}

Then I have some javascript to get the value of the checkbox. JS.js

function getValueOfCheckBox(id) {return document.querySelector(id).checked;}

Grateful for any input on how to do this!

CodePudding user response:

I think MVC works on name attributes and The name of the form control should match the MVC controller action parameters.

like this:

<input type="checkbox" id="check" name="CheckValue">

you can write the below code. this set 'name' attribute like the above code and works well:

Checkbox: @Html.CheckBoxFor(m=>m.CheckValue)
  • Related