ajax - 从 Asp.net View 页面返回带有 Ajax 调用的 View 的调用 Controller 方法

标签 ajax asp.net-mvc view 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>

单击按钮时,然后运行下面的方法:
$('#btnSearch').click(function () {
        return $.ajax({
            url: '@Url.Action("test", "ControllerName")',
            data: { Name: $('#Name').val() },
            type: 'POST',
            dataType: 'html'
        });
    });

我的 Controller 操作如下:
   public ActionResult test(string CityName) {
            ViewBag.CityName = CityName;
            return View();
                          }

当我调试我的程序时,流程来到我的 Controller Action 。但是索引网页不会路由到测试 View 页面。没有发生错误。我能为这个州做什么?

最佳答案

如果要刷新页面:

Controller :

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

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

索引.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" />
}

测试.cshtml:
@ViewBag.Name

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

如果您不想刷新页面:

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

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

索引.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

关于ajax - 从 Asp.net View 页面返回带有 Ajax 调用的 View 的调用 Controller 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39523270/

相关文章:

asp.net-mvc - 配置ELMAH : Unrecognized config section error

view - 插入到 sqlite View 中是如何工作的?

ios - 更改 UITableViewCell 样式会导致单击操作不会发生

ajax - 合并 apache 请求?

javascript - JQuery ajax DELETE 请求在 OPTIONS 阶段失败

c# - OnActionExecuted 获取状态码

c# - 如何在 MVC SimpleMembership 中锁定/解锁用户

java - 从内存中删除 View

javascript - jQuery——无法更改用 AJAX 填充的选择框的值

javascript - 像这样的 Ajax 加载动画