返回 JSON 列表并在 MVC 4 视图页面上使用



我已经使用JSON返回了一个列表,但不确定如何在MVC 4视图页面上使用返回的列表。这可能吗?

查看页面

var subjectId = value;
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/JobProfiles/FindJobProfiles/" + subjectId,
        data: "{}",
        dataType: "json",
        success: function (data)
        {
        }
    });

控制器

[HttpPost]
        public ActionResult FindJobProfiles(int? subjectId)
        {
            if (subjectId.HasValue)
            {
                Subject subject = subjectRepository.Get(subjectId.Value);
                IList<JobProfile> jobProfiles = jobProfileRepository.GetBySubject(subject.Id, false, false);
                var jobProfileList = from c in jobProfiles select new { Id = c.Id, Title = c.Title };
                return new JsonResult { Data = jobProfileList.ToList() };
            }
            else
            {
                return null;
            }
        }

查看页面显示

foreach (JobProfile job in jobProfiles)
{
    <a href="/JobProfiles/View/@job.Id" title="@job.Title">@job.Title
}

返回正确的数据,但不确定如何访问视图页面上的列表并显示数据。

div 添加到要显示结果的页面或 html 元素:

<div id="results" />

添加一个成功处理程序,用于循环结果并追加结果:

var subjectId = value;
$.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/JobProfiles/FindJobProfiles/" + subjectId,
            data: "{}",
            dataType: "json",
            success: function(data) {
                $.each(data, function(index, item) {
                        $('#results').append('<a href"/JobProfiles/View/' + item.Id +  '" title="' + item.Title +'">' + item.Title + '</a>');
                        });    
                }
            });

我假设你想在列表中显示数据。为此,您需要在 html 页面中使用带有一些 id 的div,例如 target-div。使用 jquery,您可以在 target-div 中显示列表,如下所示。

success: function (data){
   var markup='<ul>';
   for (var i = 0; i < data.length; i++)
   {
       markup+='<li>'+ data[i].itemName +'<li>';
       //itemName is key here.
   }
   markup+='</ul>';
   $('#target-div').html(markup);//this will place the list in div.
}

最新更新