将数据从MVC控制器返回到同一视图

时间:2016-09-21 18:50:57

标签: jquery ajax asp.net-mvc-4

我对asp.net MVC相当新,并遇到了一个问题,如果有人可以请我指出正确的方向。

我有一个用户输入搜索词的文本框,当按下相关搜索按钮时,它会进行Ajax调用并将文本框值传递给控制器​​。我将使用此值来使用实体框架执行SQL数据库查找。

我有点困惑如何将数据返回到同一页面。我需要继续在这个页面上作为一个JavaScript向导(jquery步骤)。

如果有人可以请我指出正确的方向,我们将不胜感激,谢谢

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

});

1 个答案:

答案 0 :(得分:2)

如果是get或post方法,则需要在声明之后使用JsonResult而不是ActionResult,然后将模型作为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
        }
    });

});
相关问题