10

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:

//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:

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

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

  return View();
}

Thanks!

2
  • Surely var length = "@Model.StudentSearchResult.count()"; results in something like var length = "5"; going to the client? And thus being a string? Yes, JavaScript is loosely typed and so it'll mostly work, but... Commented Jan 21, 2013 at 6:36
  • Thats the easy part, what I can't do is access the members of the list of objects in the view model and put them on an array Commented Jan 21, 2013 at 17:39

4 Answers 4

31

You have some invalid javascript over there.

First start by fixing your view model so that you have a compiling C# code (you were missing a property name):

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):

[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:

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:

$.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:

@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>
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your answer but the post function doesn't return a model, I know this is because I didn't post the complete code but I didn't have it at hand.
In your $.each example, how would you introduce the elements in an array if you're not taking the model from the post but from the view model itself, I am trying this: var names = new Array(); var candidates = "@Model.Candidates"; //It doesn't lets me do this for (var i = 0; i < candidates.length; i++) { var candidate = candidate[i]; alert('FirstName: ' + candidate.Name + ' LastName:' + candidate.LastName); } All I need is to populate an array with the first and last name
I understand. Please see my updated answer with an example of how you could achieve that.
1

you can use $.each of jquery to iterate the result.

$.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++) 

Comments

1

Looks like what you need is to output the user names to the client as 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.

Comments

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

instead of

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

should work.

1 Comment

Since I am using razor to access my view model I get the error that the variable "i" can't be found

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.