AspNetCore Mvc 使用 PartialView
控制器:
public IActionResult queryMongoDb(string dbname) { List<MongoDbModel> mdList = new List<MongoDbModel>(); if (!string.IsNullOrWhiteSpace(dbname)) { List<BsonDocument> document = mongo.FindFilterlData(new BsonDocument() { {"title",dbname} }); for (int i = 0; i < document.Count; i++) { MongoDbModel md = new MongoDbModel() { id = i + 1, title = document[i]["title"].ToString(), url = document[i]["title"].ToString(), likes = document[i]["likes"].ToDouble(), tags = mongo.getStrListByBson(document[i]["tags"]) }; mdList.Add(md); } } return PartialView("MongoDbPartial", mdList); }
最好在Shared中创建局部视图,这样减少了耦合度:
@model IEnumerable<MongoDbDemo.Models.MongoDbModel> <table class="table"> <thead> <tr> <th> @Html.DisplayNameFor(model => model.id) </th> <th> @Html.DisplayNameFor(model => model.title) </th> <th> @Html.DisplayNameFor(model => model.url) </th> <th> @Html.DisplayNameFor(model => model.tags) </th> <th> @Html.DisplayNameFor(model => model.likes) </th> <th></th> </tr> </thead> <tbody> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.id) </td> <td> @Html.DisplayFor(modelItem => item.title) </td> <td> @Html.DisplayFor(modelItem => item.url) </td> <td> @{ foreach (var tagsItems in item.tags) { <p>@tagsItems</p> } } </td> <td> @Html.DisplayFor(modelItem => item.likes) </td> <td> @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) | @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) | @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ }) </td> </tr> } </tbody> </table>
主视图:
@model IEnumerable<MongoDbDemo.Models.MongoDbModel> @{ Layout = null; } <script typet="text/javascript" src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script> <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <form> <p> <a asp-action="Create">Create New</a> <div> 名称:<input type="text" placeholder="条件1" id="selName"/> <input type="button" value="查询" id="butn" /> </div> <div id="datamain"> @Html.Partial("/Views/Shared/MongoDbPartial.cshtml", Model) </div> </p> </form> <script> $(function () { $("#butn").click(function () { var nameval = $("#selName").val(); alert(nameval); $.ajax({ url: "/MongoDB/queryMongoDb", data: { dbname: nameval }, type: "get", success: function (datas) { console.log(datas); $("#datamain").html(datas); } }) }) }) </script> </body> </html>
主要的思路是:
1.在主页面上定义个一div。
2.点击按钮(或者其他动作),触发div的load事件。
3.在前端js或者后台Action中避免页面缓存。
4.页面加载。