简体   繁体   中英

ASP.NET Core - How to pass a Javascript variable from View to Controller

I have a variable in a Javascript function that I want to send to the controller in order to activate a specified method.

This is the code from the javascript function in the View:

var email = response.email;    //String with an email address

 $.ajax({
     type: "POST",
     url: '@Url.Action("Login", "UsersController")',
     dataType: "html",
     data: { data: email },
                                            
     success: function (data) {
         alert('Your data updated');
         return data;
     },
     error: function (jqXHR, textStatus) {
         alert(textStatus);
     }
                                            
  });

This the method that I want to be activated in the Controller:

[HttpPost]
    public IActionResult Login(string email)
    {
        var user = _context.User.FirstOrDefault(u => u.Email == email);

        if (user != null)
        {
            SignIn(user);
            return RedirectToAction("Index", "Home");
        }

        return View("Login", "Users");
    }

Everytime I run this I get the error alert, I'm pretty new to Ajax so I'm not sure how to handle it. Thanks.

First of all, the controller name specified in the url in ajax needs to remove the Controller , that is, change the UsersController to Users .

And in the passed parameter data, change {data:email} to {email:email} , or change the Login action received parameter name from email to data to ensure that the passed parameter name is consistent with the received parameter name .

And if you want to alert the update information and then jump to the correspond view, you need to return different information in the Login action to the success method, and then judge the data in the success method and then jump .

 $.ajax({
     type: "POST",
     url: '@Url.Action("Login", "Users")',
     dataType: "html",
     data: { email: email },
     success: function (data) {
         if (data == "Success") { 
           alert('Your data updated');
           window.location.href = "/Home/Index";
        } else {
           alert("Please enter correct email!");
     }
     },
     error: function (jqXHR, textStatus) {
         alert(textStatus);
     }

  });

Action:

[HttpPost]
    public IActionResult Login(string email)
    {
        var user = _context.User.FirstOrDefault(u => u.Email == email);

        if (user != null)
        {
            SignIn(user);
            return Content("Success");
        }

         return Content("Wrong");
    }

Here is the test result:( the code in the gif is a simplified judgment.)

在此处输入图像描述

Since your parameter name in the controller is named email , you should name the property in the object you are sending email too. So your ajax call should be

$.ajax({
     type: "POST",
     url: '@Url.Action("Login", "UsersController")',
     dataType: "html",
     data: { email: email },                          //<-- here                                            
     success: function (data) {
         alert('Your data updated');
         return data;
     },
     error: function (jqXHR, textStatus) {
         alert(textStatus);
     }
                                            
  });

This will make $.ajax() send a string like email=foo@bar.com in the body of the request, that MVC can parse.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM