Zap_00
Zap_00

Reputation: 47

How to post js string to C# in ASP.NET Core MVC

I am new to ASP and I am trying to take a string in my JS code and post it to my controller so that I can use it to query my database.

JavaScript

function findEmployees(userCounty) {
    $.ajax({
        type: "POST",
        dataType: "json",
        url: '@Url.Action("Index", "Contact")',
        data: JSON.stringify(userCounty),
        contentType: "application/json",
        success: function (response) {
            alert(userCounty);
        },
        error: function (response) {
            alert("failed");
        }
    });
}

Controller

    [HttpPost]
    public ActionResult Index (string userCounty)
    {
        var query = //use linq to query database
        return View(query);
    }

I only ever get the "success" alert when I use a JsonResult function in my Controller but I need it to eventually return a LINQ query to the View(); function and that hasn't worked when using a JsonResult function. Any ideas would be helpful. I don't necessarily have to use ajax if there is a better way. I just need a way to pass the string stored in userCounty to my controller.

Upvotes: 2

Views: 848

Answers (1)

Roar S.
Roar S.

Reputation: 10939

Please change your controller method like this

[HttpPost]
public ActionResult Index([FromBody]string userCounty)
{
    var query = //use linq to query database
    return View(query);
}

For viewing the page, you'll need

[HttpGet]
public ActionResult Index()
{
  return View();
}

Upvotes: 3

Related Questions