I have this ajax code:
$('#ShowMore').click(function () {
$.ajax({
url: "/Course/GetCoursesJson",
dataType: "json",
type: "GET",
beforeSend: function () { $('#ShowMore').find('i').show(); },
success: function (data) {
**var result = "";**
$.each(data, function (key, value) {
**result = "<div class='col-md-4'>" +
"<div class='panel panel-default medisce-panel'>" +
"<div class='progress-container'>" +
"<div class='progress'>" +
"<div class='progress-bar progress-bar-custom' role='progressbar' aria-valuenow='100' aria-valuemin='0' aria-valuemax='100' style='width:" +value.Complete+"%;'>" +
"<span>" + value.Chapter + "</span>" +
"</div>" +
"</div>" +
"<div class='badge pull-right'>" + value.Complete + "%</div>" +
"</div>" +
"<h2 class='custom-title-color text-bold'>" + value.Title + "</h2>" +
"<img src='http://placehold.it/280x200' alt='"+value.Chapter+"' class='img-responsive margin-20-bottom center-block' />" +
"<button type='submit' class='btn btn-primary btn-custom'>Continue</button>" +
"</div>" +
"</div>";**
$('#ShowResult').append(result);
});
}
})
.done(function () {
$('#ShowMore').find('i').delay(1500).fadeOut(500);
});
});
***************
My question is: I want to simplified html code inside result, Can i sent Json data object to external html page or template and than render this html inside my ajax function??? I use asp.net mvc and mvvm.
You can update your action method to return view result instead of json. Have a partial view and from your action method, pass a list of items to the partial view and loop through them and render the same markup you have in your ajax call success event.
public ActionResult GetCourses()
{
List<SomeCourseViewModel> listOfCourse = GetCourseListFromSomeWhere();
return PartialView("CourseList",listOfCourse);
}
Assuming you have a view model called SomeCourseViewModel
which is a data structure to represent the data for Course.
Now in your partial view (CourseList.cshtml
) which is strongly typed to a list of your view model, loop through and render the data
@model List<SomeCourseViewModel>
@foreach(var item in Model)
{
<div class='col-md-4'>
<span>@item.Chapter</span>
<div>@item.Complete %</div>
</div>
}
I just added simple markup. You may replace it with the markup you want.
Now your ajax call's success
event can be simple and clean as this
$.ajax({
url: "/Course/GetCourses",
type: "GET",
success: function (result) {
$('#ShowResult').html(result);
}
});