ASP.NET MVC jquery自动完成,包含值和文本字段

时间:2021-06-04 03:13:56

controller

调节器

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

View:

视图:

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

I have some kind of videostore app. When I go to rent a movie I need a combobox with movies which I can select by using autocomplete. Also requirement is that only ID (value) is saved to the databas and not the text itself.

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

EDIT: here is the full working exqample

编辑:这是完整的工作实例

3 个解决方案

#1


17  

Since you are passing only a string to the Search() function on the server side, the data elements that you are passing via the $.ajax() call need to be changed.

由于您只将一个字符串传递给服务器端的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, label = r.Title, name = "MovieID" });
      return Json(routeList, JsonRequestBehavior.AllowGet);
}

$("#MovieID").autocomplete({
    source: function (request, response) {
        $.ajax({
            url: "/Transaction/Search", type: "POST", dataType: "json",
            //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 };
                }));
            },
        select: function (event, ui) {
                //update the jQuery selector here to your target hidden field
            $("input[type=hidden]").val(ui.item.id);
        }
        });
    },
});

Let me know if this works/helps!

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

#2


4  

Your .ajax() call is not specifying in an id. it's not in your data{} object, nor is it in a querystring as part of the url parameter (either approach would work).

您的.ajax()调用未在id中指定。它不在你的data {}对象中,也不在作为url参数的一部分的查询字符串中(任何一种方法都可以)。

Hence the null value in your Action method.

因此,Action方法中的null值。

Anyway, you are immediately over-writing the method's id argument with Request.QueryString["term"]. Why to do that??

无论如何,你立即用Request.QueryString [“term”]覆盖方法的id参数。为什么这样做?

Instead of asking Request for the 'term' inside the method,you just bind that to the Action method as a parameter itself like below :

您可以将其作为参数本身绑定到Action方法,而不是在方法内部请求“term”,如下所示:

public ActionResult Search(string term)
{
    var routeList = db.Movies.Where(r => r.Title.Contains(term))
            .Take(5)
            .Select(r => new { id = r.MovieID, label = r.Title, name = "MovieID" });
    return Json(routeList, JsonRequestBehavior.AllowGet);
}

#3


3  

First, you should use the following return value from your function:

首先,您应该使用函数中的以下返回值:

return { label: item.title, value: item.id };

According to the documentation you have to return objects with label and value properties (no id property). The label is what the user sees, the value is what's posted to the server.

根据文档,您必须返回具有label和value属性的对象(没有id属性)。标签是用户看到的,值是发布到服务器的值。

Second, you pass a searchText and maxResults in the Ajax call, so your action method should have two parameters: public ActionResult Search(string searchText, int maxResults).

其次,在Ajax调用中传递searchText和maxResults,因此您的action方法应该有两个参数:public ActionResult Search(string searchText,int maxResults)。

Can you apply these changes and see if it works?

您可以应用这些更改并查看它是否有效吗?

#1


17  

Since you are passing only a string to the Search() function on the server side, the data elements that you are passing via the $.ajax() call need to be changed.

由于您只将一个字符串传递给服务器端的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, label = r.Title, name = "MovieID" });
      return Json(routeList, JsonRequestBehavior.AllowGet);
}

$("#MovieID").autocomplete({
    source: function (request, response) {
        $.ajax({
            url: "/Transaction/Search", type: "POST", dataType: "json",
            //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 };
                }));
            },
        select: function (event, ui) {
                //update the jQuery selector here to your target hidden field
            $("input[type=hidden]").val(ui.item.id);
        }
        });
    },
});

Let me know if this works/helps!

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

#2


4  

Your .ajax() call is not specifying in an id. it's not in your data{} object, nor is it in a querystring as part of the url parameter (either approach would work).

您的.ajax()调用未在id中指定。它不在你的data {}对象中,也不在作为url参数的一部分的查询字符串中(任何一种方法都可以)。

Hence the null value in your Action method.

因此,Action方法中的null值。

Anyway, you are immediately over-writing the method's id argument with Request.QueryString["term"]. Why to do that??

无论如何,你立即用Request.QueryString [“term”]覆盖方法的id参数。为什么这样做?

Instead of asking Request for the 'term' inside the method,you just bind that to the Action method as a parameter itself like below :

您可以将其作为参数本身绑定到Action方法,而不是在方法内部请求“term”,如下所示:

public ActionResult Search(string term)
{
    var routeList = db.Movies.Where(r => r.Title.Contains(term))
            .Take(5)
            .Select(r => new { id = r.MovieID, label = r.Title, name = "MovieID" });
    return Json(routeList, JsonRequestBehavior.AllowGet);
}

#3


3  

First, you should use the following return value from your function:

首先,您应该使用函数中的以下返回值:

return { label: item.title, value: item.id };

According to the documentation you have to return objects with label and value properties (no id property). The label is what the user sees, the value is what's posted to the server.

根据文档,您必须返回具有label和value属性的对象(没有id属性)。标签是用户看到的,值是发布到服务器的值。

Second, you pass a searchText and maxResults in the Ajax call, so your action method should have two parameters: public ActionResult Search(string searchText, int maxResults).

其次,在Ajax调用中传递searchText和maxResults,因此您的action方法应该有两个参数:public ActionResult Search(string searchText,int maxResults)。

Can you apply these changes and see if it works?

您可以应用这些更改并查看它是否有效吗?