Call Controller Method Which Return View With Ajax Call From Asp.net View Page

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

Leave a Comment