2016-09-21 142 views
0

我对asp.net MVC相当陌生,遇到了问题,如果有人可以请我指出正确的方向。从MVC控制器返回数据返回相同的视图

我有一个文本框,用户将输入一个搜索词,当相关搜索按钮被按下时,它会进行Ajax调用并将文本框值传递给控制器​​。我将使用该值来使用实体框架执行SQL数据库查找。

我有点困惑如何将数据返回到同一页面。我需要留在这个页面上作为它的JavaScript向导(jQuery步骤)。

如果有人能请点我在正确的方向我们将不胜感激,谢谢

Index.cshtml

<div class="row"> 
<input type="text" id="SearchInput" /> 
<button class="btn btn-default" id="SearchBtn">Search</button> 
</div> 

HomeController.cs

public class HomeController : Controller 
    { 
     // GET: Home 
     public ActionResult Index() 
     { 
      return View(); 
     } 

     public ActionResult Search(string SearchInput) 
     { 
      var temp = SearchInput; 

      // TODO: look up database and return multiple rows 

      return View(); 
     } 
    } 

ajax.js

$('#SearchBtn').on('click', function() { 

    var searchQuery = $("#SearchInput").val(); 

    $.ajax({ 
     type: "POST", 
     url: "/Home/Search/", 
     data: { SearchInput: searchQuery }, 
     success: function (result) { 
      $("#result").html(result); 
     } 
    }); 

}); 
+0

是否使用'jquery.unobtrusive,ajax.js'? –

+0

不,我没有使用jquery.unobtrusive-ajax.js –

回答

2

您需要在使用JsonResult而不是ActionResult之后声明它是get还是post方法,然后将该模型作为Json返回。

SearchModel.cs

public class SearchModel 
{ 
    public string Id {get;set;} 
    public string Title {get;set;} 
    //.... 
    //add more data if you want 
} 

HomeController.cs

[HttpPost] 
public class HomeController : Controller 
{ 
    // GET: Home 
    public ActionResult Index() 
    { 
     return View(); 
    } 

    public JsonResult Search(string SearchInput) 
    { 
     var temp = SearchInput; 

     // TODO: look up database and return multiple rows 
     SearchModel searchModel = new SearchModel 
     { 
      Id = IdFromDatabase, 
      Title = TitleFromDatabase, 
      //add more if you want according to your model 
     } 

     return Json(searchModel); 
    } 
} 

ajax.js

$('#SearchBtn').on('click', function() { 

    var searchQuery = $("#SearchInput").val(); 

    $.ajax({ 
     type: "POST", 
     url: "/Home/Search/", 
     data: { SearchInput: searchQuery }, 
     success: function (result) { 
      console.log(result.Id); 
      console.log(result.Title); 
      //add more according to your model 
     } 
    }); 

}); 
相关问题