本文介绍了调用控制器方法,从 Asp.net 视图页面返回带有 Ajax 调用的视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have button. I want to route new view when i clicked the button. The button is like below:

<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>

当按钮被点击并且下面的方法运行时:

when button is clicked and than the method which is below run:

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

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

when i debug my program, flow came to my controller action. But index web page don't route to the test view page. Error is not occurred. What can i do for this state ?

推荐答案

如果要刷新页面:

控制器:

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

这篇关于调用控制器方法,从 Asp.net 视图页面返回带有 Ajax 调用的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 00:33