简体   繁体   中英

Post via ajax doesn't send data

I have the problem with post via ajax in my MVC application. I want to post a string, but in controller I get null. I found many similar problems, but still can't find a solution. My controller:

[HttpPost]
    public async Task<ActionResult> AddCompany(string data)
    {
        Company company = new Company { Name = data };
        await _context.Companies.AddAsync(company);
        await _context.SaveChangesAsync();
        return Json(new { success = true });
    }

And ajax code:

$.ajax({
        url: '/api/companyApi/',
        type: 'POST',
        data: {
            data: JSON.stringify("abc")
        },
        dataType: 'json',
        success: function() {
            alert("The company added");
        },
        error: function () {
            alert('Error! Please try again.');
        }

    });

You are trying to use /api/companyApi/ path. In order to make it work using default routing you need to make appropriate Route decorations.

Controller:

[Route("api")] //---> here is the change
public class YourControllerNameController

Action:

[HttpPost]
[Route("companyApi")] //---> here is the change
public async Task<ActionResult> AddCompany(string data)
{
    Company company = new Company { Name = data };
    await _context.Companies.AddAsync(company);
    await _context.SaveChangesAsync();
    return Json(new { success = true });
}

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