James
James

Reputation: 1501

Html.DropDownList passing as null using .val() in JSON

I am trying to get the value of an item in a dropdownlist and pass it to the controller using an ajax post, but whatever I pass keeps returning as null.

DropDownList:

<div class="form-inline">
    @Html.DropDownList("People", null, new { @id = "personID", @class = "form-control" })
    <button onClick="setTimeout( initCalendar, 5000 );" type="button" id="btnInit" data-backdrop="static" data-keyboard="false" data-toggle="modal" href="#loadingModal" class="btn btn-info">Initialise Calendar</button>
</div>

ajax post:

function initCalendar() {
    // This function will be executed when you click the element
    // show the element you want to show
    $("#loadingModal").show();

    alert($('#personID').val(""));

    //var dataRow = {
    //    'ID': $('#personID').val()
    //};

    var dataRow = $('#personID').val();

    console.log(dataRow);
    console.log($('#personID').length);

    $.ajax({
        type: 'POST',
        url: "/Event/SelectPerson",
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify(dataRow)
    });

    startCalendar();

    // Set a timeout to hide the element again
    setTimeout(function () {
        $('#loadingModal').modal('hide');
    }, 5000);
}

Controller:

    public ActionResult Index()
    {
        ViewBag.Hours = GetHoursList();
        ViewBag.People = GetPeopleList();

        return View();
    }

    // Finds all people in the database and adds them to a list for a dropdownlist.
    public List<SelectListItem> GetPeopleList()
    {
        List<SelectListItem> peopleList = new List<SelectListItem>();

        var people = from s in db.People
                     select s;

        foreach (Person person in people)
        {
            peopleList.Add(new SelectListItem
            {
                Text = person.Forename + " " + person.Surname,
                Value = person.ID.ToString()
            });
        }

        //var sortedPeopleList = (from person in peopleList
        //                        orderby person.Text
        //                        select person).ToList();

        return peopleList;
    }

    public void SelectPerson(int ID)
    {
        Person person = db.People.Where(p => p.ID == ID).FirstOrDefault();

        Session["Person"] = person;
    }

When I log the JSON, the ID is always null and I cant figure out why.

Thanks in advance.

Upvotes: 0

Views: 50

Answers (2)

user3559349
user3559349

Reputation:

The following line

alert($('#personID').val(""));

is setting the value of the element with id="personID" to null. You need to change it to

alert($('#personID').val());

Upvotes: 2

mmushtaq
mmushtaq

Reputation: 3520

try this one.

var dataRow = $('#personID').val();

Upvotes: 0

Related Questions