2016-08-24 45 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