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

前端 未结 1 1714
名媛妹妹
名媛妹妹 2020-12-11 06:36

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

相关标签:
1条回答
  • 2020-12-11 07:24

    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
    
    0 讨论(0)
提交回复
热议问题