2016-09-21 7 views
0

asp.net MVCにはかなり新しいですが、誰かが私を正しい方向に向けることができれば、問題を克服できます。MVCコントローラからのデータを同じビューに戻す

私はユーザーが検索語を入力するテキストボックスを持っています。関連する検索ボタンを押すと、Ajax呼び出しが行われ、テキストボックス値がコントローラに渡されます。この値を使用して、エンティティフレームワークを使用してSQLデータベースのルックアップを実行します。

私は、同じページにデータを戻す方法を少し困惑しています。 JavaScriptのウィザード(jquery steps)としてこのページにいなければなりません。

誰かが正しい方向に私を指すしてくださいすることができれば、それが認識されるであろう、おかげ

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

getまたはpostメソッドの場合は、その宣言の後でActionResultの代わりにJsonResultを使用し、モデルを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 
     } 
    }); 

}); 
関連する問題