0

I am trying to call an action method without affecting the view. I call the following action method

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public void Index(LoginModel login)//, string returnUrl)
{
   if (ModelState.IsValid && 
      System.Web.Security.Membership.ValidateUser(login.UserName, login.Password))
    {
        FormsAuthentication.SetAuthCookie(login.UserName, login.RememberMe);
        login.JavascriptToRun = "updateForm()";
    }
// handle error
}

by doing this

$('#loginBtn').click(function () {
        var success = false;
        var form = $('#loginForm');
        var token = $('input[name="__RequestVerificationToken"]', form).val();
        $.ajax({
            url: $(this).data('url'),
            type: 'POST',
            data: {
                __RequestVerificationToken: token,
                LoginModel: "@Model"
            },
            success: function (result) {
                alert("logged in");
            }
        });
    });

The form is in a separate view which also contains above JS-code snippet.

Everything works fine except for that the entire page reloads and since the actionmethod is void this turns out blank. I do not want anything to happen to the webpage, only to change js code snippet stored in a model which BTW is an empty function as of now.

I've looked at related posts such as ASP.NET MVC - How to call void controller method without leaving the view? but I am none the wiser.

Feels like I'v hit a wall and others' input would be much appreciated. Cheers!

Community
  • 1
  • 1
Daniel N
  • 53
  • 1
  • 11

1 Answers1

0

You can use ActionResult as a data type for Index() Action and use View() to return your javascript into it. (return JavaScriptResult())

Check out this too: Working example for JavaScriptResult in asp.net mvc

Community
  • 1
  • 1