获取参数 ajax 和 post 到 html

Get parameters ajax and post into html

我使用 Json 获取参数,如下所示:

public async Task<ActionResult> GetList(){
 var model = await db.CategoriesList.ToListAsync();
 return JSON(model, JsonRequestBehavior.AllowGet)
}

而且我知道我想从哪里获得这些类别:

<div class="megamenu-content">
  <div class="row">
    <div class="col-xs-6 col-sm-2">
      <a href="#" class="thumbnail"><img alt="150x190" src="http://www.placehold.it/100x100"></a>
    </div>
    <div class="col-xs-6 col-sm-2">
      <a href="#" class="thumbnail"><img alt="150x190" src="http://www.placehold.it/100x100"></a>
    </div>
    <div class="col-xs-6 col-sm-2">
      <a href="#" class="thumbnail"><img alt="150x190" src="http://www.placehold.it/100x100"></a>
    </div>
    <div class="col-xs-6 col-sm-2">
      <a href="#" class="thumbnail"><img alt="150x190" src="http://www.placehold.it/100x100"></a>
    </div>
    <div class="col-xs-6 col-sm-2">
      <a href="#" class="thumbnail"><img alt="150x190" src="http://www.placehold.it/100x100"></a>
    </div>
    <div class="col-xs-6 col-sm-2">
      <a href="#" class="thumbnail"><img alt="150x190" src="http://www.placehold.it/100x100"></a>
    </div>
  </div>
</div>

问题是我不太了解 Ajax,如何调用这些类别以在我的视图中显示 AJAX?

提前致谢!

这是一个完整的工作 example.Copy 它在一个新项目中 -> 运行 它 -> 了解它是如何工作的 -> 然后应用于你的解决方案:

控制器:

public class Category
{
    public string CategoryName { get; set; }
    public string ImageSrc { get; set; }
}

public class HomeController : Controller
{
    public ActionResult HomePage()
    {
        return View();
    }

    [HttpGet]
    public JsonResult GetJsonData()
    {
        var c1 = new Category { CategoryName = "Dairy", ImageSrc = "http://gilowveld.sites.caxton.co.za/wp-content/uploads/sites/97/2016/03/Dairy-products.jpg" };
        var c2 = new Category { CategoryName = "Fruits", ImageSrc = "http://science-all.com/images/wallpapers/fruits-images/fruits-images-4.jpg" };

        List<Category> categories = new List<Category> { c1, c2 };

        return Json(categories, JsonRequestBehavior.AllowGet);
    }
}

查看:

@{
    ViewBag.Title = "HomePage";
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $.getJSON("/Home/GetJsonData", null, function (data) {
            $("#result").empty();
            for (var i = 0; i < data.length; i++) {

                var image = "<img style='height:100px;width:100px;' src='" + data[i].ImageSrc + "' />"

                var div = "<div><h1>" + data[i].CategoryName + "</h1>" + image + "</div>"
                $("#result").append(div);
            }
        });
    })
</script>
<div id="result">
</div>

输出: