Html.DropDownList在JSON中使用.val()传递为null

时间:2016-04-04 13:08:07

标签: javascript jquery json ajax asp.net-mvc

我试图在下拉列表中获取项目的值,并使用ajax帖子将其传递给控制器​​,但无论我传递的是什么,都会返回为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帖子:

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);
}

控制器:

    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;
    }

当我记录JSON时,ID始终为空,我无法弄清楚原因。

提前致谢。

2 个答案:

答案 0 :(得分:2)

以下一行

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

id="personID"的元素值设置为null。您需要将其更改为

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

答案 1 :(得分:0)

尝试这个。

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