调用控制器方法,该方法从Asp.net视图页面返回带有Ajax调用的视图

Jac*_*per 5 ajax asp.net-mvc controller routes view

我有按钮 我想在单击按钮时路由新视图。该按钮如下所示:

<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>
Run Code Online (Sandbox Code Playgroud)

单击按钮时,将运行以下方法:

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

我的控制器动作如下:

   public ActionResult test(string CityName) {
            ViewBag.CityName = CityName;
            return View();
                          }
Run Code Online (Sandbox Code Playgroud)

当我调试程序时,流程进入了我的控制器动作。但是索引网页不会路由到测试视图页面。没有发生错误。在这种状态下我该怎么办?

San*_*per 6

如果你想刷新页面:

控制器:

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

public ViewResult Test()
{
    ViewBag.Name = Request["txtName"];
    return View();
}
Run Code Online (Sandbox Code Playgroud)

索引.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" />
}
Run Code Online (Sandbox Code Playgroud)

测试.cshtml:

@ViewBag.Name
Run Code Online (Sandbox Code Playgroud)

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

如果您不想刷新页面:

控制器:

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

[HttpPost]
public PartialViewResult TestAjax(string Name)
{
    ViewBag.Name = Name;
    return PartialView();
}
Run Code Online (Sandbox Code Playgroud)

索引.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>
Run Code Online (Sandbox Code Playgroud)

TestAjax.cshtml:

@ViewBag.Name
Run Code Online (Sandbox Code Playgroud)