Return JSON list and use it in MVC 4 view page
I've used JSON to return a list, but don't know how to use the returned list in the MVC 4 view page. Is this possible?
View page
var subjectId = value;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/JobProfiles/FindJobProfiles/" + subjectId,
data: "{}",
dataType: "json",
success: function (data)
{
}
});
controller
[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;
}
}
View the displayed page
foreach (JobProfile job in jobProfiles)
{
<a href="/JobProfiles/View/@job.Id" title="@job.Title">@job.Title
}
The correct data will be returned, but not sure how to access the list in the view page and display the data.
+3
source to share
2 answers
Add a div to the page for the result, or the html element you want to display:
<div id="results" />
Add a success handler that completes the result and adds it:
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>');
});
}
});
+2
source to share
I assume you want to display the data in a list. For this you need to have a div with some id say target-div in your html page. Using jquery, you can display the list in target-div as shown below.
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.
}
0
source to share