中的對象列表,因此我需要獲取學生對象列表中的學生名稱,該列表位於視圖模型中,然後通過$ .post將它們發送到服務器,後者我已經想通了,但我無法弄清楚如何遍歷對象列表。基本上,我有這樣的:Javascript:如何遍歷模型
//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.
但我會得到一個錯誤,「我」不存在的話,我怎麼能在JavaScript遍歷在我的視圖模型對象的列表,請訪問atributes和連接它們,然後將它們存儲在一個字符串數組中,以便我可以將它發送給控制器?我想控制器看起來像這樣
[HttpPost]
public ActionResult StudentSearchResult(/*other stuff I send here, */ string[] studentNames){
//stuff here
return View();
}
謝謝!
當然'var length =「@ Model.StudentSearchResult.count()」;'類似'var length =「5」;'去客戶端?因此是一個字符串?是的,JavaScript是鬆散類型,所以它將主要工作,但... –
這就是容易的部分,我不能做的是訪問視圖模型中的對象列表的成員,並將它們放在一個數組 – Ricardo