Call Controller Method Which Return View With Ajax

2020-02-06 08:28发布

问题:

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

my controller action is below:

   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 ?

回答1:

If you wants to refresh page:

Controller:

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

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

If you don't wants to refresh page:

Controller:

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