jeudi 24 août 2017

MVC Controller Different Behavior between Form Submit and Ajax call

I am pretty new to MVC and web development in general so please bear with me.

In my web app, I am trying to call a controller action via an Ajax request as I only want to refresh the partial view in my page as opposed to the entire page. Everything works properly (the Partial View is returned without refreshing the main View) except the Partial View returns the wrong values. After some debugging I discovered the error was with the Request statements in the controller action. When the controller action is called by a normal form submit, the Requests are able to get the user input values, but not when I call the controller with an Ajax request; they simply return null values.

Please see the below example, it is a much much simplified version of what I am facing. When using Ajax, the total always ends up being 0 due to the parse commands failing on a null value.

Controller:

[HttpPost]
public ActionResult Calculate() {
    string rawValue1 = Request["input1"];
    string rawValue2 = Request["input2"];

    try {
        decimal Value1 = decimal.Parse(rawValue1);
        decimal Value2 = decimal.Parse(rawValue2);
        ViewBag.Total = Value1 + Value2;
    } catch {
        ViewBag.Total = 0;
    }

    return PartialView("Banner");
}

JQuery:

 $("#calculate").on("click", function () {
    $.ajax({
        cache: false,
        dataType: 'text',
        type: "POST",
        url: "/Home/Calculate",
        success: function (data) {
            $(".banner").html(data);
        },
        error: function () {
            alert("Something went wrong in the controller");
        }
    });
    return false;
})

View:

<div class="banner"></div>
<input name="input1" type="text">
<input name="input2" type="text">
<button id="calculate">Calculate Total</button>

Partial View:

<div>
    Total:
    <span id="totalValue">@ViewBag.Total</span>
</div>




Aucun commentaire:

Enregistrer un commentaire