A Houghton A Houghton - 2 months ago 7
Ajax Question

Returning data from MVC controller back to same view

I'm fairly new to asp.net MVC and have come across a problem, if someone could please point me in the right direction.

I have a text box which a user will enter a search term, when the relating search button is pressed it makes an Ajax call and passes textbox value to controller. I'll use this value to perform a SQL database look up using entity framework.

I'm a little puzzled how to return data back to the same page. I need to stay on this page as its a JavaScript wizard (jquery steps).

If someone could please point me in the right direction it would be appreciated, thanks

Index.cshtml

<div class="row">
<input type="text" id="SearchInput" />
<button class="btn btn-default" id="SearchBtn">Search</button>
</div>


HomeController.cs

public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}

public ActionResult Search(string SearchInput)
{
var temp = SearchInput;

// TODO: look up database and return multiple rows

return View();
}
}


ajax.js

$('#SearchBtn').on('click', function () {

var searchQuery = $("#SearchInput").val();

$.ajax({
type: "POST",
url: "/Home/Search/",
data: { SearchInput: searchQuery },
success: function (result) {
$("#result").html(result);
}
});

});

Answer

You need to use a JsonResult instead of ActionResult after that declare if it is a get or post method and then return the model as Json.

SearchModel.cs

public class SearchModel
{
    public string Id {get;set;}
    public string Title {get;set;}
    //....
    //add more data if you want
}

HomeController.cs

[HttpPost]
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }

    public JsonResult Search(string SearchInput)
    {
        var temp = SearchInput;

        // TODO: look up database and return multiple rows
        SearchModel searchModel = new SearchModel
        {
            Id = IdFromDatabase,
            Title = TitleFromDatabase,
            //add more if you want according to your model
        }

        return Json(searchModel);
    }
}

ajax.js

$('#SearchBtn').on('click', function () {

     var searchQuery = $("#SearchInput").val();

    $.ajax({
        type: "POST",
        url: "/Home/Search/",
        data: { SearchInput: searchQuery },
        success: function (result) {
            console.log(result.Id);
            console.log(result.Title);
            //add more according to your model
        }
    });

});
Comments