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

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

视图:

  1. <input type="hidden" id="MovieID" name="MovieID" />
  2. <input type="text" id="SelectedMovie" value=""/>
  3. <script type="text/javascript" language="javascript">
  4. $("#SelectedMovie").autocomplete({
  5. source: function (request,response) {
  6. $.ajax({
  7. url: "/Transaction/Search",type: "POST",dataType: "json",data: { id: request.term },success: function (data) {
  8. response($.map(data,function (item) {
  9. return { label: item.label,value: item.id }; //updated code
  10. }));
  11. }
  12. });
  13. },select: function (event,ui) {
  14. $("#MovieID").val(ui.item.value);
  15. $("#SelectedMovie").val(ui.item.label);
  16. return false;
  17. }
  18. });
  19. </script>

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

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

解决方法

由于您只将一个字符串传递到服务器端的Search()函数,所以您要通过$.ajax()调用传递的数据元素需要更改.
  1. 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
  2. {
  3. id= Request.QueryString["term"];
  4.  
  5. var routeList = db.Movies.Where(r => r.Title.Contains(id))//this is a text filter no?
  6. .Take(5)
  7. .Select(r => new { id = r.MovieID,name = "MovieID" });
  8. return Json(routeList,JsonRequestBehavior.AllowGet);
  9. }
  1. $("#MovieID").autocomplete({
  2. source: function (request,response) {
  3. $.ajax({
  4. url: "/Transaction/Search",//original code
  5. //data: { searchText: request.id,maxResults: 10 },//updated code; updated to request.term
  6. //and removed the maxResults since you are not using it on the server side
  7. data: { id: request.term },success: function (data) {
  8. response($.map(data,function (item) {
  9. //original code
  10. //return { label: item.FullName,value: item.FullName,id: item.TagId };
  11. //updated code
  12. return { label: item.label,value: item.label,id: item.id };
  13. }));
  14. },ui) {
  15. //update the jQuery selector here to your target hidden field
  16. $("input[type=hidden]").val(ui.item.id);
  17. }
  18. });
  19. },});

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

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