如何从 mvc 控制器获取列表以使用 jquery ajax 查看
Posted
技术标签:
【中文标题】如何从 mvc 控制器获取列表以使用 jquery ajax 查看【英文标题】:How to get a list from mvc controller to view using jquery ajax 【发布时间】:2014-10-07 21:38:39 【问题描述】:我需要从 mvc 控制器获取列表以使用 jquery ajax 进行查看。我怎样才能做到这一点。这是我的代码。它的警告错误消息。
在控制器中
public class FoodController : Controller
[System.Web.Mvc.HttpPost]
public IList<Food> getFoodDetails(int userId)
IList<Food> FoodList = new List<Food>();
FoodList = FoodService.getFoodDetails(userId);
return (FoodList);
在视图中
function GetFoodDetails()
debugger;
$.ajax(
type: "POST",
url: "Food/getFoodDetails",
data: 'userId:"' + Id + '"',
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result)
debugger;
alert(result)
,
error: function (response)
debugger;
alert('eror');
);
【问题讨论】:
将方法返回类型更改为ActionResult,并将您的列表返回为return Json(new MyList = FodList, JsonRequestBehavior.AllowGet);
问题解决了.....???
【参考方案1】:
1-创建一个模型到 NameOf User
public class User
public int Id get; set;
public string Name get; set;
public string Family get; set;
2-创建一个ActionResult到NameOf GetUsers
public ActionResult GetUsers()
List<User> users = new List<Models.User>()
new Models.User()Id=1,Name="Diako",Family="Hasani",
new Models.User()Id=2,Name="Sina",Family="Moradi",
new Models.User()Id=3,Name="Hamid",Family="Chopani"
;
return Json(users,JsonRequestBehavior.AllowGet);
3-在您的视图中创建一个div
<div id="parent"></div>
4-将此代码写入script
<script>
$(document).ready(function ()
$.ajax(
type: "GET",
url: "/Home/GetUsers",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result)
for (var i in result)
$('#parent').append('<p>' + result[i].Name + '</p>');
,
error: function (response)
alert('eror');
);
);
</script>
【讨论】:
【参考方案2】: $(document).ready(function ()
var data = new Array();
$.ajax(
url: "list",
type: "Get",
data: JSON.stringify(data),
dataType: 'json',
success: function (data)
$.each(data, function (index)
// alert("id= "+data[index].id+" name="+data[index].name);
$('#myTable tbody').append("<tr class='child'><td>" + data[index].id + "</td><td>" + data[index].name + "</td></tr>");
);
,
error: function (msg) alert(msg);
);
);
@Controller
public class StudentController
@Autowired
StudentService studentService;
@RequestMapping(value= "/list", method= RequestMethod.GET)
@ResponseBody
public List<Student> dispalyPage()
return studentService.getAllStudentList();
【讨论】:
【参考方案3】:为什么你使用 HttpPost 的 GET 方法?并且需要返回 JsonResult。
public class FoodController : Controller
public JsonResult getFoodDetails(int userId)
IList<Food> FoodList = new List<Food>();
FoodList = FoodService.getFoodDetails(userId);
return Json (new FoodList = FoodList , JsonRequestBehavior.AllowGet);
function GetFoodDetails()
debugger;
$.ajax(
type: "GET",
url: "Food/getFoodDetails",
data: userId: Id ,
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result)
debugger;
alert(result)
,
error: function (response)
debugger;
alert('eror');
);
【讨论】:
这个解决方案对我来说非常棒。当我向首席开发人员介绍这个解决方案时,他问我“为什么是 JsonRequestBehavior.AllowGet?”。好吧,对不起,不知道,我说。他建议我进行研究以了解它,并且现在非常清楚:***.com/a/8464685/3812244 @IMAK,为什么不呢?无论如何它都会被序列化为 json 对象中的数组。【参考方案4】:我没有得到结果的原因是..我忘记在库中添加 json2.js
public class FoodController : Controller
[System.Web.Mvc.HttpGet]
public JsonResult getFoodDetails(int userId)
IList<Food> FoodList = new List<Food>();
FoodList = FoodService.getFoodDetails(userId);
return Json (FoodList, JsonRequestBehavior.AllowGet);
function GetFoodDetails()
debugger;
$.ajax(
type: "GET",
url: "Food/getFoodDetails",
data: userId: Id ,
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result)
debugger;
alert(result)
,
error: function (response)
debugger;
alert('eror');
);
【讨论】:
【参考方案5】:试试这个:
查看:
[System.Web.Mvc.HttpGet]
public JsonResult getFoodDetails(int? userId)
IList<Food> FoodList = new List<Food>();
FoodList = FoodService.getFoodDetails(userId);
return Json (new Flist = FoodList , JsonRequestBehavior.AllowGet);
控制器:
function GetFoodDetails()
debugger;
$.ajax(
type: "GET", // make it get request instead //
url: "Food/getFoodDetails",
data: userId: Id ,
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result)
debugger;
alert(result)
,
error: function (response)
debugger;
alert('error');
);
或者,如果 ajax 请求产生问题,那么您可以使用 $.getJSON
作为:
$.getJSON("Food/getFoodDetails", userId: Id , function( data ) ....);
【讨论】:
对不起,它不起作用!!它进入错误部分。 只看更新的答案就行了..@AijuThomasKurian 我需要更改 routesconfig 中的任何内容吗? 只是检查,因为在您的操作中... public JsonResult getFoodDetails(int userId)...如果来自 ajax 的用户 ID 为 null 或为空...那么它会产生问题或只使用“?”与我在回答中使用的 int 一样...@AijuThomasKurian 一切正常,直到返回部分。我有一个包含一些数据的列表。唯一的问题是如何将数据传递给查看?呼叫将转到 db,我将结果作为列表获取。【参考方案6】:你可以这样做,返回json数据并打印出来
阅读完整教程:http://www.c-sharpcorner.com/UploadFile/3d39b4/rendering-a-partial-view-and-json-data-using-ajax-in-Asp-Net/
public JsonResult BooksByPublisherId(int id)
IEnumerable<BookModel> modelList = new List<BookModel>();
using (DAL.DevelopmentEntities context = new DAL.DevelopmentEntities())
var books = context.BOOKs.Where(x => x.PublisherId == id).ToList();
modelList = books.Select(x =>
new BookModel()
Title = x.Title,
Author = x.Auther,
Year = x.Year,
Price = x.Price
);
return Json(modelList,JsonRequestBehavior.AllowGet);
$.ajax(
cache: false,
type: "GET",
url: "@(Url.RouteUrl("BooksByPublisherId"))",
data: "id": id ,
success: function (data)
var result = "";
booksDiv.html('');
$.each(data, function (id, book)
result += '<b>Title : </b>' + book.Title + '<br/>' +
'<b> Author :</b>' + book.Author + '<br/>' +
'<b> Year :</b>' + book.Year + '<br/>' +
'<b> Price :</b>' + book.Price + '<hr/>';
);
booksDiv.html(result);
,
error: function (xhr, ajaxOptions, thrownError)
alert('Failed to retrieve books.');
);
【讨论】:
以上是关于如何从 mvc 控制器获取列表以使用 jquery ajax 查看的主要内容,如果未能解决你的问题,请参考以下文章
如何在 ASP.NET MVC 中使用 jQuery ajax 方法将数据列表发送到控制器操作方法?
如何从MVC5中的jquery ajax调用中获取部分视图和JSON数据?