2016-08-24 46 views
0

我有一個代表搜索字段的@Html.EditorFor。我試圖在控制器中進行搜索,當字段中的文本被更改時。 我無法弄清楚如何每次在輸入中更改文本時進行回發,而不是在單擊提交按鈕時進行回發。如何去mtc中@ Html.EditorFor的更改回發?

型號:

public class MainWindow 
{ 
    [Key] 
    public int MainWindowId { get; set; } 
    public string SearchedString { get; set; } 
} 

查看:

@using (Html.BeginForm()) 
{ 
    <div> 
     <label>search:</label> 
     @Html.EditorFor(model => model.SearchedString, new htmlAttributes = new { @class = "form-control" } }) 
     @Html.ValidationMessageFor(model => model.SearchedString, "", new { @class = "text-danger" })  
     <input type="submit" value="search" class="btn btn-default" /> 
    </div> 
} 

控制器:

[HttpPost] 
public ActionResult Index([Bind(Include = "MainWindowId,SearchedString")] MainWindow mw) 
{ 
    ManageProduct mp = new ManageProduct(); 
    if (ModelState.IsValid) 
    { 
     //search code 
     return View("Index",mw); 
    } 
    return View(mw); 
} 
+2

你想要什麼,自動完成這樣的功能? –

+0

你應該使用javascript的ajax請求 –

回答

0

使用Ajax提交表單。我將在我的例子中使用jQuery。

收聽編輯呈現的<input>的更改。爲了達到這個目的,我們使用編輯器提供給HTML輸入的ID作爲jQuery選擇器(不要更改ID,因爲MVC模型綁定器期望它處於特定格式)。使用瀏覽器開發工具(F12)查找ID。

您還需要爲表單元素提供一個ID,以便我們可以序列化它以獲取發佈數據。還提供了一個可以顯示結果的佔位符。

@using (Html.BeginForm("Index", "YourController", FormMethod.Post, new { id = "formId" })) { 

<div id="placeholderId"></div> 
@Html.EditorFor(model => model.SearchedString, new htmlAttributes = new { @class = "form-control" } }) 

JS功能後的形式,嵌入在剃刀視圖:

<script type="text/javascript"> 
function postForm() { 
    $.ajax({ 
     url: $('#formId').attr('action'), 
     type: 'POST', 
     data: $('#formId').serialize(), 
     success: function(resultData) { 
      if (resultData) { 
       // update some placeholder element with the received data 
       $('#placeholderId').html(resultData); 
      } 
     } 
    }); 
} 

JS聽輸入的變化,嵌入在剃刀視圖。聆聽keyup事件,因爲change只會在輸入失去焦點後纔會觸發。在這裏,我假定編輯給出了輸入id="SearchedString"(可能會有所不同,例如,如果這是呈現爲部分視圖)。

$('#SearchedString').on('keyup', function() { 
     postForm(); 
}); 
</script> 

爲了防止您的服務器beeing與請求淹沒在用戶類型,看看jQuery.debounce

+0

我試過了@Georg Patscheider說的,而且聽衆從未達到過。我如何將監聽器連接到輸入? – Anonymous

+0

請確保輸入有css類'searchInput'。 –

+0

這是輸入的樣子:'@ Html.EditorFor(model => model.SearchedString,new {htmlAttributes = new {@class =「form-control searchInput」}})' – Anonymous