C# Javascript:如何遍历模型中的对象列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14433406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript: How to iterate through list of objects in Model
提问by Ricardo
so I need to get to fetch the names of students in a list of student object that is in a view's model then send them to the server via $.post, the latter I have figured it out but I can't figure out how to iterate through the list of objects. Basically I have this:
所以我需要在视图模型中的学生对象列表中获取学生的姓名,然后通过 $.post 将它们发送到服务器,后者我已经弄清楚了,但我不知道如何遍历对象列表。基本上我有这个:
//Student object
public class Student
{
public string FirstName { get; set; }
public string LastName { get; set; }
//Like a bunch of other attributes here
}
This is the model in the view:
这是视图中的模型:
//StudentSearchResult ViewModel
public class StudentSearchResult {
public IEnumerable<Student> { get; set;}
}
At first I though of just sending the student list object as is, but it may not be a good idea as it is bundled with too many attributes (it gave me this 'circular' error when I tried to send the model) and I only really need to send the concatenated FirstName and LastName to the controller using the $.post method I already have. I tried things like these:
起初我虽然只是按原样发送学生列表对象,但这可能不是一个好主意,因为它捆绑了太多属性(当我尝试发送模型时它给了我这个“循环”错误),我只真的需要使用我已经拥有的 $.post 方法将连接的 FirstName 和 LastName 发送到控制器。我试过这样的事情:
var names = []
var length = "@Model.StudentSearchResult.count()";
for (int i = 0; i < length; i++)
{
names[] = "@Model.StudentSearchResult[i].Name + @Model.StudentSearchResult[i].LastName"
}
//$.post function here that calls the controller and send the concatenated names of each student in studentsearchresult.
But I'd get an error that "i" doesn't exists so, how can I iterate in javascript through the list of objects in my view model, access the atributes and concatenate them and then store them on an array of strings so that I may send it to the controller? I imagine the controller would look like this
但是我会得到一个错误,即“i”不存在,所以我如何在 javascript 中遍历视图模型中的对象列表,访问属性并将它们连接起来,然后将它们存储在一个字符串数组中,以便我可以把它发送给控制器吗?我想控制器看起来像这样
[HttpPost]
public ActionResult StudentSearchResult(/*other stuff I send here, */ string[] studentNames){
//stuff here
return View();
}
Thanks!
谢谢!
采纳答案by Darin Dimitrov
You have some invalid javascript over there.
你那里有一些无效的javascript。
First start by fixing your view model so that you have a compiling C# code (you were missing a property name):
首先修复您的视图模型,以便您可以编译 C# 代码(您缺少属性名称):
public class StudentSearchResult
{
public IEnumerable<Student> Students { get; set;}
}
Then assuming your controller actions sends a JSON result to the client (this ensures that the view model is properly JSON encoded and that the application/json
response content type header is sent):
然后假设您的控制器操作向客户端发送一个 JSON 结果(这确保视图模型正确 JSON 编码并application/json
发送响应内容类型标头):
[HttpPost]
public ActionResult StudentSearchResult(/*other stuff I send here, */ string[] studentNames)
{
StudentSearchResult model = ... //stuff here to populate your view model
return Json(model);
}
you could easily iterate on the client using the $.each()
function:
您可以使用以下$.each()
函数轻松地在客户端上进行迭代:
var studentNames = ['name1', 'name2'];
$.post('/Students/StudentSearchResult', studentNames, function(result) {
var students = result.Students;
$.each(students, function() {
alert('FirstName: ' + this.FirstName + ' LastName:' + this.LastName);
});
});
or even a plain ol' for
loop if you prefer:
for
如果您愿意,甚至可以使用简单的 ol'循环:
$.post('/Students/StudentSearchResult', studentNames, function(result) {
var students = result.Students;
for (var i = 0; i < students.length; i++) {
var student = students[i];
alert('FirstName: ' + student.FirstName + ' LastName:' + student.LastName);
}
});
UPDATE:
更新:
It looks like I have I made a mistake by believing that you were performing an AJAX request. Instead what you need is access the model properties in javascript. Here's how this could be done:
看起来我认为您正在执行 AJAX 请求是我犯了一个错误。相反,您需要的是访问 javascript 中的模型属性。这是如何做到的:
@model StudentSearchResult
<script type="text/javascript">
var students = @Html.Raw(Json.Encode(Model.Students));
// students is a javascript array that will look like this:
// students = [{"FirstName":"fn1","LastName":"ln1"}, {"FirstName":"fn2","LastName":"ln2"}, ...];
for (var i = 0; i < students.length; i++) {
var student = students[i];
alert('FirstName: ' + student.FirstName + ' LastName:' + student.LastName);
}
</script>
回答by ndlinh
for (var i = 0; i < length; i++)
instead of
代替
for (int i = 0; i < length; i++)
should work.
应该管用。
回答by Ravi Gadag
you can use $.each of jquery to iterate the result.
您可以使用 $.each of jquery 来迭代结果。
$.each(yourModel,function(){//do with loop});
and for the error. you made mistake in declaration of loop variable
和错误。你在循环变量的声明中犯了错误
for (var i = 0; i < length; i++)
回答by Jeffrey Zhao
Looks like what you need is to output the user names to the client as JSON? Try this:
看起来您需要将用户名作为 JSON 输出到客户端?尝试这个:
var names = @Model.StudentSearchResult.Select(s => new { s.FirstName, s.LastName }).ToList();
I'm not quite familiar with the Razor syntax, but I think you can still understand the code above.
我对 Razor 语法不是很熟悉,但我认为你仍然可以理解上面的代码。