我正在开发一个 asp.net MVC Web 应用程序,其中我使用 Linq to Sql 通过 jquery 和 ajax 从数据库获取结果。我的模型有以下代码
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;
}
我的 Controller 有以下代码
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;
}
在我看来包含
$("#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);
}
});
}
});
我在我的 asp 页面中得到以下结果
{ EmpID = 1,CommentText = sss,时间 = 1/27/2012 2:20:49 AM } { EmpID = 1,CommentText = aaa,时间 = 1/27/2012 2:46:07 AM } { EmpID = 1,CommentText = aaa,时间 = 1/27/2012 2:50:23 AM } { EmpID = 1,CommentText = Munazza,时间 = 1/27/2012 2:58:29 AM } { EmpID = 1, CommentText = Jawad,时间 = 1/27/2012 3:00:51 AM } { EmpID = 1,CommentText = xx,时间 = 1/28/2012 11:56:59 AM } { EmpID = 1,CommentText = ss,时间 = 1/28/2012 12:35:00 PM }
我想获得不带大括号且不带属性的结果,即 1 ss 1/27/2012
问候
最佳答案
问题是您正在调用 ToString
关于匿名类型。您现有的Comment
模型类包含太多数据?如果没有,您可以使用:
public List<Comment> GetComments(long problemID)
{
return _objectModel.Comments.Where(c => c.ProblemID == problemID)
.ToList(); // Force evaluation
}
然后,您可以更改 Controller 来转换此 List<Comment>
转换为 Javascript 可以理解的 AJAX。
如果您真的只想要没有属性的字符串,您可以将原始代码更改为:
public IEnumerable<string> GetComments(long problemID)
{
var query = from c in _objectModel.Comments
where c.ProblemID == problemID
select new { c.EmpID, c.CommentText, c.Time };
return query.AsEnumerable() // Do the rest locally
.Select(c => string.Format("{0} {1} {2"}, c.EmpID,
c.CommentText, c.Time));
}
您还应该更改 Controller 代码以使用 String.Join
或StringBuilder
- 否则,由于重复的字符串连接,您将遇到 O(n2) 问题...
关于c# - Linq to SQL 获取多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9043759/