2012-10-08 25 views
0

在我看来,我有;MVC jQuery的自动完成,我如何拿起选定的ID?

@using (Ajax.BeginForm("AddExistingSite", new AjaxOptions { UpdateTargetId = "siteRows" })) 
      { 

       <input type="text" name="q" style="width: 800px" 
         data-autocomplete="@Url.Action("SiteSearch", "DataService", new { contractId = @Model.Contract.ContractId })" /> 
       <input type="submit" value="Add site to contract" /> 
      } 

在我的控制器我有

public ActionResult SiteSearch(string term, int contractId) 
    { 
     using (var db = new SherryGreenGroupEntities()) 
     { 
      var sites = db.Sites 
       .Include("SiteContracts") 
       .Where(x => x.SiteContracts.All(y => y.ContractId != contractId || y.EndDate.HasValue) && 
        x.Address.Contains(term)) 
       .Take(10) 
       .Select(x => new { id = x.SiteId, label = x.Address }).ToList(); 
      return this.Json(sites, JsonRequestBehavior.AllowGet); 
     } 
    } 

我已经建立了jQuery的;

$(":input[data-autocomplete]").each(function() { 
    $(this).autocomplete({ source: $(this).attr("data-autocomplete") }); 
}); 

现在自动完成工作,但我想知道的是我该怎么办拿起所选项目的ID,这样我可以把它发布到控制器?

回答

1

当前,您的表单中只有一个文本字段,它将保存选定的值。如果您需要相应的ID,你可以添加一个隐藏字段将被用于存储这样的信息:

@using (Ajax.BeginForm("AddExistingSite", new AjaxOptions { UpdateTargetId = "siteRows" })) 
{ 
    <input type="text" name="q" style="width: 800px" data-autocomplete="@Url.Action("SiteSearch", "DataService", new { contractId = @Model.Contract.ContractId })" /> 
    <input type="hidden" name="itemId" class="itemId" /> 
    <input type="submit" value="Add site to contract" /> 
} 

,然后订阅select事件自动完成的,并与相应的值更新:

$(':input[data-autocomplete]').each(function() { 
    $(this).autocomplete({ 
     source: $(this).attr('data-autocomplete'), 
     select: function (event, ui) { 
      $(this).closest('form').find('.itemId').val(ui.item.value); 
     } 
    }); 
}); 

现在的目标控制器作用是微不足道的同时获得标签和标识内:

[HttpPost] 
public ActionResult AddExistingSite(string q, string itemId) 
{ 
    ... 
} 

显然,这一切都只是一个原始例子。在真实应用程序中,您不应该在视图中对输入字段进行硬编码,但应该使用HTML助手来生成它们,并且您显然应该使用视图模型。