所以我需要获取视图模型中学生对象列表中的学生姓名,然后通过$.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();
}
谢谢!
var length = "@Model.StudentSearchResult.count()";
会导致像var length = "5";
这样的东西传递给客户端吗?因此成为一个字符串?是的,JavaScript 是弱类型的,所以它大多数情况下可以工作,但是... - T.J. Crowder