Archive for May, 2016

Why is a Boolean value in MVC required

I had a Boolean value in my model that worked fine when it was set to true, but when set to false, the ModelState was reporting an error for that value, saying it was required. This isn’t what I wanted. So I found a Stack Overflow question about the exact same thing.

To get around this issue, I had to change my property definition my Boolean became a nullable Boolean:

public bool? IsNewUser { get; set; }

Leave a comment

Textbox not updating from jQuery AJAX call

I had a friendly little piece of JavaScript code to return a string to the calling code:

function getDescByCode(code) {
    var returnVal;

    $.ajax({
        url: "http://www.scott.bla/api/ReturnMyStringValue",
        type: "GET",
        data: { code: code }
    })
    .done(function (data) {
        returnVal = data;
    });
    
    return returnVal;
}

This method was being called by an onchange event assigned to an MVC drop down list to update a textbox, so when a user changed the value of the DDL, the associated textbox would be changed to the value returned from the Web API call, which was called from the function above:

@Html.DropDownListFor(m => m.MyCode, 
(IEnumerable<SelectListItem>)Application["Codes"], 
"--Select--", 
new { @onchange = "$('#MyDesc').val(getDescByCode(this.value));" })
   @Html.TextBoxFor(m => m.MyDesc)

The problem was that the text box wasn’t being updated. However, if I added an alert inside the jQuery method, I could see that the data was, in fact, being returned from the Web API called as expected:

    .done(function (data) {
       alert(data);    // Worked
    });

The problem was solved by adding the “async: false” line to the AJAX call. The full working method is:

function getDescByCode(code) {
    var returnVal;

    $.ajax({
        url: "http://www.scott.bla/api/MyStuff",
        type: "GET",
        async: false,
        data: { code: code }
    })
    .done(function (data) {
        returnVal = data;
    });
    
    return returnVal;
}

Leave a comment

Attaching events to checkboxes

I needed attach events to a group of checkboxes. So in my HTML page, I have a list of checkboxes, and a div tag to hold the results:

      <input id="1" type="checkbox" class="cb" /Do Stuff
      <input id="2" type="checkbox" class="cb" />Do More Stuff
      

I then have jQuery code to attach the actual events, and I call the attachCheckboxEvents function below when the page loads. Note that I am looping through the “cb” classes to get the DOM items I need:

      function attachCheckboxEvents() {
       $(".cb").click(function (e) {
           $("#results").html('<p>' + $(this).attr('id') + '</p>');
       });
      }

Leave a comment