获取参数ajax并发布到html中

时间:2016-06-07 21:49:28

标签: c# jquery asp.net-mvc asp.net-ajax

我使用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将这些类别调用到我的视图中?

提前致谢!

1 个答案:

答案 0 :(得分:0)

这是一个完整的工作示例。在新项目中复制它 - &gt;运行它 - &gt;了解它是如何工作的 - &gt;然后申请你的解决方案:

<强>控制器:

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>

<强>输出:

Fetching JSON data in ASP.NET MVC example