1

I need to pass search string to action method.

View:

<div>
  <input id="search" type="text" placeholder="Search">
  <div id="submitButton"></div>
</div>
<script type="text/javascript">
$("#submitButton").click(function () {
    var options = {};
    options.url = "/Section/Search";
    options.type = "POST";
    options.data = JSON.stringify({ t: $("#search").val() });
    options.contentType = "application/json";
    options.dataType = "json";
    $.ajax(options);
});
</script>

I need to call this action method and take search string.

Controller: Section/Search

[HttpGet]
public ActionResult Search(string SearchResults)
{
    using (var db = new LambertonEntities())
    {
        var article = db.News.ToList();
        return View(article);
    }
}
Mamun
  • 66,969
  • 9
  • 47
  • 59
user2224493
  • 259
  • 3
  • 5
  • 13

2 Answers2

2

Don't get your code becouse you have ajax POST method and HttpGet Controller, but still.

If you want to pass parameters and use POST you can just pass data params as you already do:

$("#submitButton").click(function () {
    var options = {};
    options.url = "/Section/Search";
    options.type = "POST";
    options.data = { SearchResults: $("#search").val() };
    options.contentType = "application/json";
    options.dataType = "json";
    $.ajax(options);
});

But if you want to use GET i recomend to use $.param() method like this:

$("#submitButton").click(function () {
    var options = {};
    options.url = "/Section/Search?" + $.param({ SearchResults: $("#search").val() });
    options.type = "GET";
    options.contentType = "application/json";
    options.dataType = "json";
    $.ajax(options);
});

The best adwantage of using $.param() if you don't need to create url param string at your own no matter how complicated your object is.

If you want to redirect to this action you shouldn't use ajax. Your Controller method should allow GET.

$("#submitButton").click(function () {
    window.location.href = "/Section/Search?" + $.param({ SearchResults: $("#search").val() });
});

This will redirect you to search page in same window.

$("#submitButton").click(function () {
    window.open("/Section/Search?" + $.param({ SearchResults: $("#search").val() }));
});

This will redirect you to search page in new window. For more info.

Community
  • 1
  • 1
teo van kot
  • 12,350
  • 10
  • 38
  • 70
0

try this:

JS

$("#submitButton").click(function () {
var options = {};
options.url = "/Section/Search";
options.type = "POST";
options.data = JSON.stringify({ searchResults: $("#search").val() });
options.contentType = "application/json";
options.dataType = "json";
$.ajax(options);

});

Server

[HttpPost]
public ActionResult Search(string SearchResults)
{
    using (var db = new LambertonEntities())
    {
        var article = db.News.ToList();
        return View(article);
    }
}
el_vil16
  • 11
  • 2