locked
Ajax BeginForm does not page back RRS feed

  • Question

  • User521171331 posted

    Hi,

    @using (Ajax.BeginForm("CalculateWithAjaxJsonBeginForm", "Home", new AjaxOptions
    {
        HttpMethod = "POST",
        OnSuccess = "SuccessMessage", // JS
        OnFailure = "FailMessage", // JS
        UpdateTargetId = "result" // p tag ID
    }, new {@id = "myForm" }))
    {
        @Html.TextBox("num1", null, new { @type = "number" })
        @Html.TextBox("num2", null, new { @type = "number" })
    
        <input type="submit" value="Submit form with ajax" id="btnSubmit" />
    
    
        <p id="result"></p>
    }

     [HttpPost]
            public ActionResult CalculateWithAjaxJsonBeginForm(int num1, int num2)
            {
                ViewBag.Result = num1 + num2;
                int responseText = num1 + num2;
               // return Json(new { success = true, responseText = num1 + num2 }, JsonRequestBehavior.AllowGet);
                return Json(responseText, JsonRequestBehavior.AllowGet);
            }

    I have this code which manage to come to the controller. But it does not return back to the view. Any idea what went wrong?

    Monday, April 16, 2018 8:21 AM

Answers

  • User-369506445 posted

    hi

    your code is correct , but you must sure add below jquery

    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

    also i complete your code :

    @using (Ajax.BeginForm("CalculateWithAjaxJsonBeginForm", "Home", new AjaxOptions
    {
        HttpMethod = "POST",
        OnSuccess = "SuccessMessage", // JS
        OnFailure = "FailMessage", // JS
       
    }, new { @id = "myForm" }))
    {
        @Html.TextBox("num1", null, new { @type = "number" })
        @Html.TextBox("num2", null, new { @type = "number" })
    
        <input type="submit" value="Submit form with ajax" id="btnSubmit" />
    
    
        <p id="result"></p>
    }
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
    <script language="javascript">
        function SuccessMessage(data) {
            $("#result").html(data);
        }
    </script>

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, April 16, 2018 11:19 AM