2016-03-01 15 views
1

昨天我問了這個問題。一位專家建議我使用Ajax。如果用戶存在,數據庫表中的數據的完整表單文本框?

請使用MVC5創建表單時,我需要在分機號旁邊創建一個按鈕鏈接。當用戶輸入分機號碼並單擊它旁邊的按鈕時,分機號碼將傳送到JasonResult以在表格中搜索。如果擴展名存在,那麼創建視圖中的文本框將顯示他的名字,位置和徽章。

這裏是我的控制器。

public JsonResult EmployeeInfo(string extension, Ticket ticket) 
    { 
     var result = from r in db.CUSTOMERS 
        where r.BADGE_NUMBER == extension 
        select new { r.BADGE_NUMBER, r.LOCATION, r.NAME }; 

     return Json(result, JsonRequestBehavior.AllowGet); 
    } 

這裏是代碼在視圖中。

<div class="form-group"> 
     @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" }) 
     <div class="col-md-10"> 
      @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } }) 
      @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" }) 
     </div> 
    </div> 



    <div class="form-group"> 
     @Html.LabelFor(model => model.Phone, htmlAttributes: new { @class = "control-label col-md-2" }) 
     <div class="col-md-10"> 
      @Html.EditorFor(model => model.Phone, new { htmlAttributes = new { @class = "form-control" } }) 
      @Html.ValidationMessageFor(model => model.Phone, "", new { @class = "text-danger" }) 

      <input type="submit" id="GetInfo" value="search"/> 


      <script type="text/jscript"> 
       $('#GetInfo').click(function() { 
        $.getJSON('/Tickets/EmployeeInfo/' + $('#Phone').val(), function (data) { 

         $('#rData').html(items); 
        }); 
       }) 
      </script> 
     </div> 
    </div> 

任何人都可以幫助我嗎? 謝謝,

+0

將返回'json'不是一個視圖,這樣你就不能使用'$( '#RDATA')HTML(項目。 );' - 您需要更新現有元素的值 - 例如'$(someElement).val(data.LOCATION);' - 但不清楚你想要更新的元素。並從你的方法中刪除'Ticket ticket'參數。 –

+0

並將'type =「submit」'改爲'type =「按鈕」'(您不要提交表單) –

+0

@StephenMuecke謝謝,我想返回與填充文本框中的名稱,位置和徽章相同的創建表單嗎?你能告訴我如何寫在$(someElement).val(data.LOCATION);? – user3415175

回答

1

這聽起來像你使用MVC控制器,它返回一個視圖,所以這是行不通的。我建議你用這樣的路線(未測試當然)加e網阿比控制器:

[Route("Tickets/EmployeeInfo/{extension}")] 
public Task<IHttpActionResult> EmployeeInfo(string extension) 
{ 
    var result = from r in db.CUSTOMERS 
        where r.BADGE_NUMBER == extension 
        select new { r.BADGE_NUMBER, r.LOCATION, r.NAME }; 

    return result; 
} 

這個web API路線將提供您的JSON作爲結果。您可以像現在使用JavaScript一樣調用此路線。 你也應該改變你的按鈕鍵入按鈕:

<input type="submit" id="GetInfo" value="search"/> 

<input type="button" id="GetInfo" value="search"/> 
+0

'MVC控制器'可以像OP一樣返回'json'。 –

相關問題