2012-10-08 24 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助手來生成它們,並且您顯然應該使用視圖模型。