Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to post data to ASP.NET MVC controller using AJAX?

I wanted to send Mobile number and EmailID using jQuery AJAX to my MVC controller to check whether these details are already exist in the database or not.

When I am using the [HttpPost] attribute on my action method, I am getting error as:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at url.

If I remove the [HttpPost] attribute, my action method is getting called, but all the values received in action method argument are null.

Below is the action method code:

public class LogOnModel
{
    public string Mobile { get; set; }
    public string EmailID { get; set; }
}

[HttpPost]
[AllowAnonymous]
///AJAXService/LogOnAjax
public ActionResult LogOnAjax(LogOnModel obj)
{
    return Json(true);
}

Below is my AJAX call:

var LoginModel = {
    'Mobile': "ASH",
    'EmailID': "MITTAL",
};
$.ajax({
    url: 'http://localhost:51603/AJAXService/LogOnAjax',
    type: 'GET',
    contentType: 'application/json',
    dataType: 'jsonp',
    data: JSON.stringify(LoginModel),
    success: function (result) {
        if (result == true) {
            window.location = "/Dashboard";
        } else {
            $QuickLoginErrors.text(result);
        }
    }
});

I have placed the code below in my web.config file to avoid CORS errors:

<customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
like image 388
Ashish Mittal Avatar asked Mar 14 '23 06:03

Ashish Mittal


2 Answers

If the AjaxService controller is in the same project as the View you're working on:

var LoginModel = {
    Mobile: "ASH",
    EmailID: "MITTAL"
};

$.ajax({
    url: '@Url.Action("LogOnAjax","AJAXService")', // try to use Url Helper when possible
    type: 'POST', // use Get for [HttpGet] action or POST for [HttpPost]
    //contentType: 'application/json', not needed
    //dataType: 'jsonp', jsonp is for sending to a site other than the current one.. 
    data: LoginModel, // no need to stringify
    success: function (result) {
        if (result == true) {
            window.location = "/Dashboard";
        } else {
            $QuickLoginErrors.text(result);
        }
    }
});
like image 96
JamieD77 Avatar answered Mar 27 '23 03:03

JamieD77


Keep the [HttpPost] and add this line right before your $.ajax line:

$.support.cors = true;

Also change your $.ajax method to match your [HttpPost]. Change the line:

type: 'GET',

to

method: 'POST',

Note: This only worked in IE for me. Chrome still refused to complete the Ajax call. However, that was a while back and I'm not sure if the newer versions of Chrome will work with this line.

Very important note: Only use this line in development. Do not compile your App with this line.

like image 35
Racil Hilan Avatar answered Mar 27 '23 04:03

Racil Hilan