【问题标题】:Call Controller Method Which Return View With Ajax Call From Asp.net View Page调用控制器方法,从 Asp.net 视图页面返回带有 Ajax 调用的视图
【发布时间】:2017-01-24 04:44:45
【问题描述】:

我有按钮。当我单击按钮时,我想路由新视图。按钮如下:

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

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

【问题讨论】:

  • ajax 的全部目的是保持在同一页面上。如果要在 POST 方法中重定向,则不要使用 ajax。或者,如果您要添加在 test() 方法中返回的视图,则处理 success 回调并更新 DOM(尽管在这种情况下 ViewBag.CityName = CityName; 毫无意义) - 例如success: function(response) { $(someElement).html(response); }

标签: ajax asp.net-mvc view controller routes


【解决方案1】:

如果要刷新页面:

控制器:

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

【讨论】:

  • 谢谢,我在最后一行苦苦挣扎,将数据放入表中,如此简单直接,gr8回答
猜你喜欢
  • 2020-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多