异步收索的作用简单来说就是:在不更新整个网页的情况下更新你想改变的网页某个部分。
下面是实现:
1.准备工作
在mvc5 中要用Ajax,首先要添加jQuery的Ajax文件。方法:右击项目--管理NuGet程序包--查找jQuery--找到关于Ajax的,然后安装。
2。 Index.页面
@model IEnumerable<ajax异步.Models.ajax>@{ ???Layout = "~/Views/Shared/_Layout.cshtml";}<script src="~/Scripts/jquery-3.3.1.js"></script> ???<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script> ???<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>@using (Ajax.BeginForm("Indec","Home", ??//方法和控制器 ?????new AjaxOptions ????//怎么实现Ajax功能 ?????{ ?????????InsertionMode = InsertionMode.Replace, ?//覆盖 ?????????HttpMethod = "Get", ?????????UpdateTargetId = "serch", ?//目标:id为search的元素 ?????})){ ???<input type="text" name="idd" /> ???<input type="submit" name="submit" value="Find" />}@*将要刷新的页面弄成partial页面,否则会将整个页面又放在这个地方*@@Html.Partial("Index1",Model) ?
3.控制器
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using ajax异步.Models;namespace ajax异步.Controllers{ ???public class HomeController : Controller ???{ ???????// GET: Home ???????private dbcontext db = new dbcontext(); ???????public ActionResult Index( string idd) ???????{ ???????????????if (Request.IsAjaxRequest()) //如果是Ajax请求,也就是点了查询,那么返回查询的数据 ???????????????{ ???????????????var people = from m in db.ajax ????????????????????????????where m.id.ToString() == idd ????????????????????????????select m; ???????????????return PartialView("Index1", people);//返回要更新的partial页面 ???????????????} ???????????????else//第一次不是Ajax请求,返回数据库的全部数据 ???????????????{ ???????????????????return View(db.ajax.ToList()); ???????????????} ???????????} ???????} ???}
4,partial页面
@model IEnumerable<ajax异步.Models.ajax><div id="serch"> ???<table border="1" class="tab-content"> ???????<tr> ???????????<td>id </td> ???????????<td>name </td> ???????</tr> ???????@foreach (var item in Model) ???????{ ???????????<tr> ???????????????<td>@Html.DisplayFor(c => item.id)</td> ???????????????<td>@Html.DisplayFor(c => item.name)</td> ???????????</tr> ???????} ???</table></div>
实现的方式很简单 主要就是Ajax辅助方法 然后安装要用的jQuery文件 最后把要更新的部分设置为partial页面
Ajax异步表单简单实现收索功能
原文地址:https://www.cnblogs.com/zhangyuhao/p/10088851.html