I am developing an asp.net MVC web app in which I am using Linq to Sql for getting the results from database through jquery and ajax. My model has following code
public IEnumerable<string> getComments(long problemID)
{
var comment = from c in _objectModel.Comments
where c.ProblemID == problemID
select new { c.EmpID, c.CommentText, c.Time }.ToString();
return comment;
}
and my controller has following code
public string GetComments(string problemid)
{
List<string> collection = _discussionRepository.getComments(Convert.ToInt32(problemid)).ToList();
string comments = null;
foreach (string item in collection)
{
comments += item + "\n";
}
return comments;
}
and in my view contains
$("#btnPostComment").click(function () {
var strdata = {
problemID: $("#problemID").val(),
commentText: $("#_1").val(),
empID: $("#empID").val(),
agree: 0,
disagree: 0
};
$.ajax({
type: "POST",
url: "<%= Url.Action("PostComment", "Discussion") %>",
data: strdata,
error: function(msg){
alert("error" + msg);
},
success: function (msg) {
var id = { problemid : $("#problemID").val()};
$.ajax({
type: "GET",
url: "<%= Url.Action("GetComments", "Discussion") %>",
data: id,
error: function(msg){
alert("error2" + msg);
},
success: function (msg) {
$("#commentdiv").html(msg);
}
});
}
});
and I am getting the following result in my asp page
{ EmpID = 1, CommentText = sss, Time = 1/27/2012 2:20:49 AM } { EmpID = 1, CommentText = aaa, Time = 1/27/2012 2:46:07 AM } { EmpID = 1, CommentText = aaa, Time = 1/27/2012 2:50:23 AM } { EmpID = 1, CommentText = Munazza, Time = 1/27/2012 2:58:29 AM } { EmpID = 1, CommentText = Jawad, Time = 1/27/2012 3:00:51 AM } { EmpID = 1, CommentText = xx, Time = 1/28/2012 11:56:59 AM } { EmpID = 1, CommentText = ss, Time = 1/28/2012 12:35:00 PM }
I want to get the result without braces and without properties i.e 1 ss 1/27/2012
Regards
The problem is that you’re calling
ToStringon the anonymous type. Does your existingCommentmodel class contain too much data? If not, you can just use:You’d then change your controller to convert this
List<Comment>into AJAX which the Javascript could understand.If you really only want strings without properties, you could just change your original code to:
You should also change your controller code to either use
String.Joinor aStringBuilder– as otherwise you’re going to have an O(n2) problem due to repeated string concatenation…