简体   繁体   English

Javascript:如何遍历模型中的对象列表

[英]Javascript: How to iterate through list of objects in Model

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. 所以我需要在视图模型中的学生对象列表中获取学生的名字,然后通过$ .post将它们发送到服务器,后者我已经弄明白但我无法弄清楚如何遍历对象列表。 Basically I have this: 基本上我有这个:

//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. 起初我虽然只是按原样发送学生列表对象,但它可能不是一个好主意,因为它捆绑了太多属性(当我尝试发送模型时它给了我'循环'错误)而且我只真的需要使用我已经拥有的$ .post方法将连接的FirstName和LastName发送到控制器。 I tried things like these: 我尝试过这样的事情:

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”不存在的错误,如何通过我的视图模型中的对象列表迭代javascript,访问属性并连接它们然后将它们存储在字符串数组中,以便我可以把它发送给控制器吗? I imagine the controller would look like this 我想控制器看起来像这样

[HttpPost]
public ActionResult StudentSearchResult(/*other stuff I send here, */ string[] studentNames){
   //stuff here

  return View();
}

Thanks! 谢谢!

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循环,如果你喜欢:

$.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. 看起来我因为相信您正在执行AJAX请求而犯了一个错误。 Instead what you need is access the model properties in javascript. 相反,您需要访问javascript中的模型属性。 Here's how this could be done: 以下是如何做到这一点:

@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>
for (var i = 0; i < length; i++) 

instead of 代替

for (int i = 0; i < length; i++) 

should work. 应该管用。

you can use $.each of jquery to iterate the result. 你可以使用$ .each的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++) 

Looks like what you need is to output the user names to the client as JSON? 看起来你需要的是将用户名作为JSON输出到客户端? Try this: 试试这个:

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语法不太熟悉,但我认为您仍然可以理解上面的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM