从MVC 3中的ActionResult类型方法返回一个JSon数组到$ .ajax
我有一个TreeView帮助器,它包含类别列表及其链接。 我这样做了
@helper TreeView(FavouriteLinksXmlMVC3.Controllers.HomeController cat) { cat = new FavouriteLinksXmlMVC3.Controllers.HomeController(); try { foreach(FavouriteLinksXmlMVC3.Models.CategoriesControl list_category in cat.Categories) { @list_category.Name @if(list_category.hasChild) { } } } catch(Exception e) { Response.Write( e.ToString() ); } }
好。 它的工作就像一个魅力。
我做了一个函数,它使用JQuery获取链接信息:
$(".file").click(function () { $.ajax({ url: '@Url.Action("GetLinkInfo")', data: { cat_name: $(this).attr("categ_name"), url: $(this).attr("id") }, type: "GET", success: function (data) { //alert(data.Name + " " + data.Url + " " + data.Description); var make = "Name: " + data.Name + " Url: " + data.Url + " Description " + data.Description + "
"; $("#details").html(make); } }); });
和GetLinkInfo
[HttpGet] public ActionResult GetLinkInfo( string cat_name, string url ) { if ( string.IsNullOrEmpty( cat_name ) ) throw new ArgumentNullException( "GetLinkInfo cat_name" ); if ( string.IsNullOrEmpty( url ) ) throw new ArgumentNullException( "GetLinkInfo url" ); var c = this.Categories.Find( x => x.Name == cat_name ); string name1="", url1="", descr1=""; bool done = false; if ( c != null ) { foreach ( var p in c.Links ) { if ( p.Url == url ) { name1 = p.Name; url1 = p.Url; descr1 = p.Description; done = true; break; } } } if ( done ) { return Json( new { Name = name1, Url = url1, Description = descr1 }, JsonRequestBehavior.AllowGet ); } else { return View(); } }
我解决了这个问题
[HttpGet] //controller public JsonResult GetCategoryInfo( string cat_name ) { if ( string.IsNullOrEmpty( cat_name ) ) throw new ArgumentNullException( "GetCategoryInfo cat_name" ); var c = this.Categories.Find( x => x.Name == cat_name ); if ( c != null ) { List lk = null; if ( c.hasChild ) { lk = new List(); foreach ( var p in c.Links ) { lk.Add( p ); } } else { lk = new List( 0 ); } return this.Json(lk,JsonRequestBehavior.AllowGet); } else { return this.Json(new List( 0 ),JsonRequestBehavior.AllowGet); } }
和JQuery
$(".folder").click(function() { var find_id = $(this).attr("id"); $.ajax({ type: "GET", url: '@Url.Action("GetCategoryInfo")', dataType : 'json', data: { cat_name: find_id }, success: function (response) { // $("#details").html(response.toString()); var make = ""; make += "Name Url Description "; $.each(response, function (index, lk) { make += "" + lk.Name + " " + lk.Url + " " + lk.Description + " "; }); make += "
"; $("#details").html(make); } }); });
尝试将public ActionResult GetCategoryInfo()
更改为public JsonResult GetCategoryInfo()
我想ActionResult
返回类型可能会导致问题,但这只是一种预感!
上述就是C#学习教程:从MVC 3中的ActionResult类型方法返回一个JSon数组到$ .ajax分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1031008.html