2016-09-16 70 views
1

我有按钮。我想在点击按钮时路由新视图。此按钮类似于如下:呼叫控制器方法返回视图与Ajax呼叫从Asp.net查看页面

<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(); 
          } 

当调试我程序,流程来到我的控制器操作。但是索引网页不会路由到测试视图页面。没有发生错误。我能为这个状态做些什么?

+1

AJAX的全部目的是留在同一页上。如果你想在POST方法中重定向,那么不要使用ajax。或者,如果你要添加你在'test()'方法中返回的视图,则处理'success'回调并更新DOM(尽管在这种情况下“ViewBag.CityName = CityName;”是毫无意义的)。 '成功:function(response){$(someElement).html(response); }' –

回答

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