首页 > 代码库 > Ajax retrieve JSON data and Html data from MVC Controllers in ASP.NET MVC
Ajax retrieve JSON data and Html data from MVC Controllers in ASP.NET MVC
一、
准备好后台测试数据,过程略
二、客户端处理
@{ ViewBag.Title = "Index";}<h2>Ajax Demo</h2><div style="width: 600px; "> <div style="background-color:lightgray"> <h2>Meals</h2> </div> <p>Click the button to Get Meals with an Ajax call</p> <input id="btnAjax" name="btnAjax" type="button" value=http://www.mamicode.com/"Get Meals" /> <div id="meals" style="background-color:lightskyblue"></div> <div id="jsonResult" style="background-color:lightsalmon"></div></div><div style="background-color:lightpink;display:none;" id="updateMealDiv"> <table> <tr> <th>Name</th> <th>Comments</th> <th>Picture</th> </tr> <tr> <td><input type="text" id="txtName" name="txtName" /></td> <td><input type="text" id="txtComment" name="txtComment" /></td> </tr> </table> <input type="button" value=http://www.mamicode.com/"update meal" id="btnUpdateMeal" name="btnUpdateMeal"></div><script type="text/javascript"> $("#btnAjax").click(function () { $.ajax({ url: ‘/AjaxDemo/GetMeal‘, contentType: ‘application/html; charset=utf-8‘, type: ‘Get‘, datatype: ‘html‘ }) .success(function (data) { $("#meals").html(data); $("#updateMealDiv").show().appendTo($("#meals")); }) .error(function (xhr, status, errorThrown) { alert(errorThrown); }) }); $("#btnUpdateMeal").click(function () { var nameVal = $("#txtName").val(); var commentVal = $("#txtComment").val(); $.ajax({ url: ‘/AjaxDemo/GetJsonString‘, data: JSON.stringify({ name: nameVal, comment: commentVal }), type: ‘Post‘, contentType: "application/json; charset=utf-8" }) .success(function (data) { var resultStr = "<ul><li>" + data.newName + "</li><li>" + data.newComment + "</li></ul>"; $("#jsonResult").html(resultStr); }) .error(function (xhr, status, errorMsg) { alert(errorMsg); }) });</script>
三、Controller 处理
使用Json.stringify()来处理json字符串
public class AjaxDemoController : Controller { private Db dbContext = new Db(); // // GET: /AjaxDemo/ public ActionResult Index() { return View(); } public ActionResult GetMeal() { Meal[] meals = dbContext.Meals.Where(m => m.Id <= 5).ToArray(); return PartialView("GetMeals", meals); } public ActionResult GetJsonString(string name, string comment) { return Json(new { newName = name + "Luxuan", newComment = comment + "LLLLL" }); } public ActionResult UpdateMeal(string mName, string comment) { IList<Meal> mealList = dbContext.Meals.ToList(); Meal updatedMeal = mealList.Where(m => m.Name == mName).Single(); updatedMeal.Name = mName; updatedMeal.Comments = comment; dbContext.SaveChanges(); mealList = mealList.Where(m => m.Id <= 5).ToArray(); return PartialView("GetMeals", mealList); } }
四、运行结果
Ajax retrieve JSON data and Html data from MVC Controllers in ASP.NET MVC
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。