2016-09-21 143 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 
     } 
    }); 

}); 
相關問題