使用JSON的MVC自动完成文本框在Post上返回NULL

时间:2015-12-08 16:45:23

标签: c# json asp.net-mvc

我希望我的搜索框能够自动填充数据库中的值。当我在搜索框中输入内容时,它正确地命中控制器,但无论我尝试什么,字符串值都返回NULL。这是我的代码:

查看(部分视图):

@using (Html.BeginForm("SearchBar", "Home", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    <div class="container">
        <div class="searcharea">
            @Html.TextBox("SearchString", null, new { placeholder = "Type search here..." } )
            <input type="submit" />
        </div>
    </div>

}

<script type="text/javascript">
    $(function () {
        $("#SearchString").autocomplete({
            source: "/Home/AutoCompleteSearch",
            minLength: 1,
            select: function (event, ui) {
                if (ui.item) {
                    $("#SearchString").val(ui.item.value);
                    $("form").submit();
                }
            }
        });
    });
</script>

控制器:

public JsonResult AutoCompleteSearch(string SearchString)
{
    var values = from s in db.Customers
                              select s.CustomerNumber;

    var namelist = values.Where(n => n.ToLower().StartsWith(SearchString));
    return Json(namelist, JsonRequestBehavior.AllowGet);
}

因此,当我输入搜索框时,我来到此控制器,但字符串SearchString为NULL。我正在关注tutorial

1 个答案:

答案 0 :(得分:0)

public JsonResult AutoCompleteSearch(string SearchString)
{
    var values = from s in db.Customers
                              select s.CustomerNumber;

    var namelist = values.Where(n => n.ToLower().StartsWith(SearchString.ToLower()));
    return Json(namelist, JsonRequestBehavior.AllowGet);
}