Blog Stats
  • Posts - 56
  • Articles - 0
  • Comments - 6
  • Trackbacks - 0

 

Thursday, January 24, 2013

Setting HTML.CheckBoxFor Values in MVC 4 View from Json return using jQuery Ajax Script


I’m an MVC/jQuery noobie and this one really got my goat for while. The problem was handling the bit field in SQL Server which was treated as a checkbox field in MVC.

Here’s how you can set a checkbox value based the the user’s selection from dropdown list on the same view:

Model:

public string Field_Ref_Name { get; set; } // the dropdown list 
public bool CoreField { get; set; } // the checkbox

Controller:

From the Get ActionResult method to populate the dropdown list.  
ViewBag.projectConditionWitRefFieldsDropdownList = 
                new SelectList(refFieldList, selectedField);

The JsonResult method called by the jQuery script in the view.

public JsonResult GetFieldAttributes(string selectedField)
        {
            string a = selectedField;
            bool b = false;
            if (!(selectedField.Contains("some value")))
            {
                b = true;
            }
            
            var dataParms = new { aA = a, aB = b };
            return Json(dataParms, JsonRequestBehavior.AllowGet);
        }

View:

The script, which gets the bool from the Json result and sets the checkbox. Note I had to use the “click” event to set the checkbox. All efforts to use some sort of checked true or false approach failed. The trick is the conditional logic of the data.aB boolean return value.

<script type="text/javascript">
     $(function() {
            $("#ddlField").change(function() {
                var selectedItem = $(this).val();
                $.ajax({
                    cache: false,
                    type: "GET",
                    url: "@(Url.Action("GetFieldAttributes", "ConditionDetails"))",
                    data: { "selectedField": selectedItem},
                    success: function (data) {
                        $("#DataType").val(data.aA);
                        if (data.aB) {
                            var chk = $('#CoreField').is(':checked');
                            if (!(chk)) {
                                $("#CoreField").click();
                            }
                        }
                        else {
                            var chk = $('#CoreField').is(':checked');
                            if (chk) {
                                $("#CoreField").click();
                            }
                        }
                    },
                    error:function (xhr, ajaxOptions, thrownError){
                        alert('Failed to return core and type field attributes.');

                    }  
                });
            });
        });
    </script>

From the razor code to display the page.

@using (Html.BeginForm()) 
        {
            @Html.ValidationSummary(true)

            <fieldset>
                <legend>Condition_Details</legend>

                <div class="editor-label">
                    @Html.LabelFor(model => model.Field_Ref_Name)
                </div>
                <div class="editor-field">
                    @if (@ViewBag.projectFilterSelected)
                    {
                        @Html.DropDownListFor(model => model.Field_Ref_Name, 
                        ViewBag.projectConditionWitRefFieldsDropdownList as SelectList, 
                            string.Empty, new { @id = "ddlField", style = "font-size: .85em; font-weight: normal;" })
                    }
                    else
                    {
                        @Html.EditorFor(model => model.Field_Ref_Name)
                    } 
                    @Html.ValidationMessageFor(model => model.Field_Ref_Name)
                </div>

                <div class="editor-label">
                    @Html.LabelFor(model => model.DataType)
                </div>
                <div class="editor-field">
                    @Html.EditorFor(model => model.DataType)
                    @Html.ValidationMessageFor(model => model.DataType)
                </div>

                <div class="editor-label">
                    @Html.LabelFor(model => model.CoreField)
                </div>
                <div class="editor-field">
                    @Html.CheckBoxFor(model => model.CoreField)
                    @Html.ValidationMessageFor(model => model.CoreField)
                </div>

            </fieldset>
        }
 

 

Copyright © Bob Hardister