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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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();
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x