2016-09-16 6 views
1

ボタンがあります。私はボタンをクリックしたときに新しいビューをルーティングしたい。ボタンは以下のようなものです:Asp.netからAjax呼び出しで返信するコールコントローラメソッドビューページ

<button type="button" id="btnSearch" class="btn btn-warning" style="height:35px;width:120px"> <i class="fa fa-search" aria-hidden="true"></i> <translate>Search</translate> </button> 

ボタンをクリックして実行を下回っている方法よりもされている場合:

$('#btnSearch').click(function() { 
     return $.ajax({ 
      url: '@Url.Action("test", "ControllerName")', 
      data: { Name: $('#Name').val() }, 
      type: 'POST', 
      dataType: 'html' 
     }); 
    }); 

私のコントローラのアクションは以下の通りです:

public ActionResult test(string CityName) { 
      ViewBag.CityName = CityName; 
      return View(); 
          } 

私は私をデバッグするときプログラムは、私のコントローラのアクションに流れました。しかし、インデックスWebページはテストビューページにルーティングされません。エラーは発生していません。この状態で私は何をすることができますか?

+1

アヤックスの全体の目的は、同じページに滞在することです。 POSTメソッドでリダイレクトする場合は、ajaxを使用しないでください。あるいは、 'test()'メソッドで返すビューを追加する場合は、 'success'コールバックを処理してDOMを更新します(この場合、' ViewBag.CityName = CityName; 'は無意味です)。 '成功:function(レスポンス){$(someElement).html(レスポンス); } ' –

答えて

2

ページを更新したい場合:

コントローラー:

public ActionResult Index() 
{    
    return View(); 
} 

public ViewResult Test() 
{ 
    ViewBag.Name = Request["txtName"]; 
    return View(); 
} 

Index.cshtml:

@using (Html.BeginForm("Test", "Home", FormMethod.Post)) 
{ 
    <input type="submit" id="btnSearch" class="btn btn-warning" style="height:35px;width:120px" value="Search"/> 
    <label>Name:</label><input type="text" id="txtName" name="txtName" /> 
} 

Test.cshtml:

@ViewBag.Name 

=========================================== ==

あなたはページを更新したいと考えていない場合:

コントローラー:

public ActionResult Index() 
{    
    return View(); 
} 

[HttpPost] 
public PartialViewResult TestAjax(string Name) 
{ 
    ViewBag.Name = Name; 
    return PartialView(); 
} 

Index.cshtml:

<input type="button" id="btnSearch" class="btn btn-warning" style="height:35px;width:120px" value="Search"/> 
<label>Name:</label><input type="text" id="txtName" name="txtName" /> 


<script> 
$('#btnSearch').click(function() { 
    $.ajax({ 
     url: '@Url.Action("TestAjax", "Home")', 
     data: { Name: $("#txtName").val() }, 
     type: 'POST', 
     success: function (data) { 
      $("#divContent").html(data); 
     } 
    }); 
}); 
</script> 

TestAjax.cshtml:

@ViewBag.Name 
関連する問題