ASP.NET MVC jquery自动填充值和文本字段

前端之家收集整理的这篇文章主要介绍了ASP.NET MVC jquery自动填充值和文本字段前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
调节器
public ActionResult Search(string id)
{
     id= Request.QueryString["term"];         
     var routeList = db.Movies.Where(r => r.Title.Contains(id))
                   .Take(5)
                   .Select(r => new { id = r.MovieID,label = r.Title,name = "MovieID" });
     return Json(routeList,JsonRequestBehavior.AllowGet);
}

视图:

<input type="hidden"   id="MovieID"  name="MovieID" />
<input type="text" id="SelectedMovie" value=""/>
<script type="text/javascript" language="javascript">
   $("#SelectedMovie").autocomplete({
       source: function (request,response) {
           $.ajax({
              url: "/Transaction/Search",type: "POST",dataType: "json",data: { id: request.term },success: function (data) {
              response($.map(data,function (item) {                                
                return { label: item.label,value: item.id }; //updated code
               }));
             }
         });
     },select: function (event,ui) {
         $("#MovieID").val(ui.item.value);
         $("#SelectedMovie").val(ui.item.label);
         return false;
     }
  });
</script>

我有一些视频商店应用程序当我去租一部电影时,我需要一个带有电影的组合框,我可以使用自动完成来选择.
还要求的是,只有ID(值)被保存到数据库中,而不是文本本身.

编辑:这里是完整的工作示例

解决方法

由于您只将一个字符串传递到服务器端的Search()函数,所以您要通过$.ajax()调用传递的数据元素需要更改.
public ActionResult Search(string id)//I think that the id that you are passing here needs to be the search term. You may not have to change anything here,but you do in the $.ajax() call
{
      id= Request.QueryString["term"];

      var routeList = db.Movies.Where(r => r.Title.Contains(id))//this is a text filter no?
                        .Take(5)
                        .Select(r => new { id = r.MovieID,name = "MovieID" });
      return Json(routeList,JsonRequestBehavior.AllowGet);
}
$("#MovieID").autocomplete({
    source: function (request,response) {
        $.ajax({
            url: "/Transaction/Search",//original code
            //data: { searchText: request.id,maxResults: 10 },//updated code; updated to request.term 
            //and removed the maxResults since you are not using it on the server side
            data: { id: request.term },success: function (data) {
                response($.map(data,function (item) {
                    //original code
                    //return { label: item.FullName,value: item.FullName,id: item.TagId }; 
                    //updated code
                    return { label: item.label,value: item.label,id: item.id };
                }));
            },ui) {
                //update the jQuery selector here to your target hidden field
            $("input[type=hidden]").val(ui.item.id);
        }
        });
    },});

让我知道这是否有效/有帮助!

原文链接:https://www.f2er.com/aspnet/250545.html

猜你在找的asp.Net相关文章