0

I have an MVC4 application, and on the layout (master page for the oldies), I have some javascript:

<script type="text/javascript">
        $(document).ready(function () {
            $('.btnSubmit').on('click', function () {
                var data = { username: $('.txtUsername').val(), password: $('.txtPassword').val(), rememberMe: $('.cbRemember').val() };

                $.ajax({
                    url: '@Url.Action("LoginUser", "User")',
                    type: "POST",
                    contentType: "application/json",
                    data: JSON.stringify(data),
                    cache: false,
                    async: true,
                    success: function (result) {
                        console.log(result.toString());
                        if (result.Success == 'true') {
                            window.location = '@Url.Action("Index", "Home")';
                        } else {
                            alert(result.Message);
                        }
                    },
                    error: function () {
                        alert("Error in input");
                    }

                });
            });
        });
    </script>

This simply logs in a user.

This is working fine.

However, on another screen I now have some new javascript, which does similar function, by taking data from a form, and passing it to a controller to handle.

<script type="text/javascript">
        $(document).ready(function () {
            $('.btnSubmitNewCard').on('click', function () {
                var data = { cardNumber: $('.txtNewCardNumber').val(), cardHolder: $('.txtNewCardHolder').val(), expiryMonth: $('.txtNewExpiryMonth').val(), expiryYear: $('.txtNewExpiryYear').val(), active: $('.txtNewActive').val(), accountId: $('.Id').val() };

                $.ajax({
                    url: '@Url.Action("SaveBankCard", "BankAccount")',
                    type: "POST",
                    contentType: "application/json",
                    data: JSON.stringify(data),
                    cache: false,
                    async: true,
                    success: function (result) {
                        console.log(result.toString());
                        if (result.Success == 'true') {
                           // window.location = '@Url.Action("Index", "Home")';
                        } else {
                            alert(result.Message);
                        }
                    },
                    error: function () {
                        alert("Oh no");
                    }

                });
            });
        });
    </script>

When I click the save button that this code is linked to, the code fires, the controller method goes well, the data is stored, but then, when I refresh the screen, I get an 'Undefinied' error coming from the LOGIN script above. It seems to fire when the page is reloaded. I am unsure why it's firing. It should just load, ready to fire, but it seems to be called, and fails.

The controller that it calls is this:

public ActionResult SaveBankCard(string cardNumber, string cardHolder, int expiryMonth, int expiryYear, string active, int accountId)
{
    var card = new AccountCardDto
        {
            Id = 0,
            AccountId = accountId,
            Active = active == "on",
            CardHolderName = cardHolder,
            CardNumber = cardNumber,
            ExpiryDate = new DateTime(expiryYear, expiryMonth, 1)
        };

    int id = new BankAccountService().SaveCard(card);
    return RedirectToAction("EditBankAccount", new { bankAccountId = accountId });

}

The problem happens on the RedirectToAction... when that view reloads, which includes the Layout, the Layout javascript fires.

EDIT: I now see that it's the btnSubmitNewCard javascript that is fired twice. Once when the click event happens (expected), and then again when the postback happens. Why is the second event happening?

Craig
  • 18,074
  • 38
  • 147
  • 248
  • Why are you doing RedirectToAction in the first place instead of using plain form/redirecting manually from Java Script? Btw, How come that view reloads after ajax call if you do not render it at all? – vmg Jan 03 '14 at 23:56
  • I'm pretty new to this. If I an doing something wrong, do tell. The controller method fuss some work, then, I was hoping it would basically just go back to the calling page. I'm not sure about your second question. – Craig Jan 04 '14 at 00:11
  • By default you can't redirect with ajax request. You need to do that manually with javascript. Ajax request will follow HTTP 302 redirect code. See these question: http://stackoverflow.com/questions/8436611/redirecttoaction-mvc-3-after-ajax-call http://dataplex.org/2009/11/asp-net-mvc-ajax-redirecttoaction/ http://stackoverflow.com/questions/5041899/asp-net-mvc-ajax-post-redirecttoaction-not-working – vmg Jan 04 '14 at 00:21

2 Answers2

1

Check with this: -

$('.btnSubmitNewCard').click(function () {...});
PSL
  • 123,204
  • 21
  • 253
  • 243
user3115056
  • 1,266
  • 1
  • 10
  • 25
0

You are getting Undefined in the line that checks status:

if (result.Success == 'true') {

Because result contains string with html response of the view for the EditBankAccount action and does not have "Success" property. You can put breakepoint in debugger and see. You can use debugger; statement as breakpoint

vmg
  • 9,920
  • 13
  • 61
  • 90
  • Thanks. I'm confused why that script is even bring executed though, because my login button isn't being clicked. – Craig Jan 04 '14 at 04:17
  • Ah, I see it's actually NOT my login code that is failing, but the 'btnSubmitNewCard' click seems to be fired when the page is reloaded. How do I prevent this? It's fired on the click event, and then again when the page is reloaded. – Craig Jan 04 '14 at 04:40
  • in order to use debugger; statement you need to run developer tools in browser. For example, press F12 in internet Explorer or Firefox BEFORE you expect breakpoint to be hit. – vmg Jan 04 '14 at 09:18