[英]ASP.NET MVC get list from controller with ajax
I search solution for my problem in search engine and stackoverflow.I find a lot of answer but nothing of them didn't help to me. 我在搜索引擎和stackoverflow中搜索问题的解决方案。我找到了很多答案,但是没有一个对我没有帮助。 Here is my controller:
这是我的控制器:
[HttpGet]
public JsonResult Get()
{
var cl = new List<Category>();
cl.Add(new Category()
{
Name = "C#"
});
cl.Add(new Category()
{
Name = "MVC"
});
return Json(cl.ToList(),JsonRequestBehavior.AllowGet);
}
and category class is below: 类别类别如下:
public class Category
{
public string Name { get; set; }
}
In my view,I want to list each item in the data. 在我看来,我想列出数据中的每个项目。
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "GET",
url: '@Url.Action("Get","Category")',
contentType: "application/json;charset=utf-8",
data: { a: "testing" },
dataType: "json",
success: function(data) {
//<ul>
//<li>C#</li>
//<li>MVC</li>
},
error: function () { alert('error....'); }
});
});
</script>
How can I do it? 我该怎么做?
You could use the shorter getJSON
like this: 您可以这样使用较短的
getJSON
:
var getUrl = '@Url.Action("Get")';
var resultDiv = $('#result');
$.getJSON(getUrl, data: { a: "testing"}, function (data) {
resultDev.append('<ul>')
$.each(data, function (index, item) {
resultDiv.append($('<li/>', { text: item.name }));
});
});
Without seeing your markup I have made the assumption of outputting to a div just for demonstration purposes. 在没有看到您的标记的情况下,我假设仅出于演示目的而输出到div。
Thanks @hutchonoid. 谢谢@hutchonoid。 because of you I find solution.I am using your code and update my code:
由于您的原因,我找到了解决方案。我正在使用您的代码并更新我的代码:
$(document).ready(function() {
$.ajax({
type: "GET",
url: '@Url.Action("Get","Category")',
contentType: "application/json;charset=utf-8",
data: { a: "testing" },
dataType: "json",
success: function (data) {
$.each(data, function(index,item) {
$("#cat").append('<li>'+item.Name+'</li>');
});
},
error: function () { alert('error....'); }
});
Others are the same. 其他都一样。
public JsonResult Get(int userId)
{
using (Entities context = new Entities())
{
var appNo = context.UserApp.Where(p => p.UserId == userId && p.Status > 0).ToList();
var builder = new StringBuilder();
appNo.ForEach(p =>
{
builder.AppendFormat("<li><a href='https://demos.url.com>{0}</a></li>", p.Id);
});
return Json(builder.ToString(), JsonRequestBehavior.AllowGet);
}
}
<script>
$(document).ready(function () {
$("#dropDownListUser").change(function () {
var val = $(this).val();
$.ajax({
url: '@Url.Action("Get", "User", new {Area = "AREANAME"})',
data: { 'userId': val },
type: 'GET',
success: function (data) {
$('#ulid').html(data);
}
});
});
});</script>
<ul id="ulid"></ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.