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. 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:
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.
Thanks @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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.