Linq到SQL获取多个列
Linq to SQL get multiple columns
我正在开发一个asp.net MVC web应用程序,在该应用程序中,我使用Linq到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;
}
我的控制器有以下代码
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,Time=1/27/2012 2:27:49 AM}{EmpID=1,Comment Text=aaa,Time=1/227/27/2012 2:46:07 AM}{EmpID=1,CommentText=ss,Time=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
}
然后,您可以更改控制器,将这个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));
}
您还应该将控制器代码更改为使用String.Join
或StringBuilder
,否则由于重复的字符串连接,您将出现O(n2)问题。。。
查看客户端代码,您似乎期望从ajax调用中获得格式化的html,但您只是返回ToString(正如Jon Skeet所说)。
如果这是您的意图,那么您应该将字符串格式化为有效的HTML,但最好以json格式返回数据,并将其转换为HTML客户端。
相关文章:
- 尝试在移动优先应用程序中从 SQL 数据库获取数据时出错
- 如何使用 ajax 从 sql Server 获取单选按钮的值,并表示列表单选按钮
- 如何在不刷新页面的情况下从 PHP 中的 SQL Server 数据库获取数据
- 如何将所有动态id的arrey值获取到javascript VAR CID,以便在sql中找到匹配项
- 从ajax中获取数据,同时将其放入sql查询中
- 无法从从sql数据库读取的javascript函数中获取返回数组
- 调用Javascript函数来获取sql查询的结果集,并将它们打印在html表中
- 如何在express中从sql中获取值
- 获取从 SQL/PHP 到 Javascript 的日历事件
- 如何从按钮函数中获取要在 AJAX 和 sql 查找中使用的值
- 当按下按钮时从SQL和PHP获取行内容,即使调用id
- 从javascript获取变量,并在php上为jQuery-Seat-Charts构建一个sql查询
- Ajax 从 sql 查询中获取结果
- 在 Ajax 提交后获取新的 Sql ID
- 我有一个javascript倒计时,但我需要倒计时才能从我的sql数据库中获取日期
- 如何在执行php文件以从SQL数据库获取信息时上传数据以用作过滤器
- Ajax / js刷新,限制显示/从php / sql获取的内容
- 获取SQL数据错误
- 使用PHP获取SQL数据,然后将Array发送到Javascript
- Javascript - 获取 SQL 消息