所以我需要在视图模型中的学生对象列表中获取学生的姓名,然后通过 $.post 将它们发送到服务器,后者我已经弄清楚了,但我不知道如何遍历对象列表。基本上我有这个:
//Student object
public class Student
{
public string FirstName { get; set; }
public string LastName { get; set; }
//Like a bunch of other attributes here
}
这是视图中的模型:
//StudentSearchResult ViewModel
public class StudentSearchResult {
public IEnumerable<Student> { get; set;}
}
起初我虽然只是按原样发送学生列表对象,但这可能不是一个好主意,因为它捆绑了太多属性(当我尝试发送模型时它给了我这个“循环”错误)而且我只真的需要使用我已经拥有的 $.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.
但是我会得到一个错误,“i”不存在所以,我如何在 javascript 中遍历我的视图模型中的对象列表,访问属性并将它们连接起来,然后将它们存储在字符串数组中,以便我可以将它发送给控制器吗?我想控制器看起来像这样
[HttpPost]
public ActionResult StudentSearchResult(/*other stuff I send here, */ string[] studentNames){
//stuff here
return View();
}
谢谢!