$.each(someData.split(',') => returns concatenated string, instead of array of items
I'm using asp.net mvc - ajax with jQuery... I've a model type named "Books" that contains a property "TableOfContents" this property contains data in the following format:
TableOfContents = "1,2,4,6,9,17,28";
Json action method, that reuturn Book object look like this:
public JsonResult GetBook(int id) {
return Json(_bookRepository.Current(id), .....AllowGet);
}
Following style of list images that I want to display.
In C# (Razor) I can do this,
var splitted = Model.TableOfContents.Split(‘,’);
@foreach(var number in splitted) {
<li><img src=”@Url.Content(“~/Content/Images/img-“ + number + “.gif”)” /> </li>
}
This code 100% works and shows images as shown in the above image.
The same thing I want to done with jQuery because I’m using ASP.NET MVC Ajax with jQuery. Here is the jQuery script through with I get data from MVC via jQuery.
<script type="text/javascript">
function GetBook(id) {
var url = '@Url.Content("~//Monthly/CurrentBook?id=")' + id;
$.post(url,
null,
function (book) {
开发者_开发技巧 $('#bookResult' + book.ID).html(
'<a href="@Url.Content("~/BookDetails/")' + book.ID + '">Click to View Details</a>'
+ '<div><p style=" text-align:center;">'
+ '<a href="' + monthly.URL + '"><button style="background-image:url(@Url.Content("~/Content/Images/download-pdf.gif")); width:200px; height:70px;" /></a>'
+ '**<!-- Here I want to use jQuery Code for displaying Table of content Images -->**'
+ '</p></div>');
},
'json'
);
}
</script>
I used jQuery code like this:
$.each(book.TableOfContents.split(','), function(number) {
+ '<li><img src="img-' + number + '.gif" /></li>'
}
But it displays result as: "1,2,3,17,90" (in string format instead of displaying images)
In ASP.NET MVC Razor, I can display list of images like this:
var splitted = Model.TableOfContents.Split(‘,’);
@foreach(var number in splitted) {
<li><img src=”@Url.Content(“~/Content/Images/img-“ + number + “.gif”)” /> </li>
}
http://alhadith.cz.cc (this webite's main page displays list of images with ASP.NET MVC Razor)
If you have
var book={TableOfContents:"1,2,4,6,9,17,28"};
as your object with data then in <head>
add:
$(function(){
$('#list').empty();
var TableOfContentsSplit=book.TableOfContents.split(',');
$.each(TableOfContentsSplit,function(number){
$('#list').append('<li><img src="img-'+TableOfContentsSplit[number]+'.gif" /></li>\n');
});
});
and in <body>
add:
<ul id="list"></ul>
At the end you'll get:
<ul id="list">
<li><img src="img-1.gif"></li>
<li><img src="img-2.gif"></li>
<li><img src="img-4.gif"></li>
<li><img src="img-6.gif"></li>
<li><img src="img-9.gif"></li>
<li><img src="img-17.gif"></li>
<li><img src="img-28.gif"></li>
</ul>
Cheers G.
精彩评论