0

In jquery, I have:

for (var i = 0; i < authorizations.length; i++) {
    //2014-04-14: Issue #49
    showvendornumber = "";
    vendornumber = '@Model.GetVendorNumber(authorizations[i].VendorId)';
}

And I'm getting an error for the index i in @Model.GetVendorNumber(authorizations[i].VendorId).

How do I get that iterator in scope in order to access the model values?

EDIT model:

    public string GetVendorNumber(int id)
    {
        if (this.VendorNumber == null)
        {
            this.VendorNumber = this.repository.GetVendorNumber(id);
        }
        return this.VendorNumber;
    }
3
  • What does your model look like? Commented Apr 14, 2014 at 18:02
  • I've edited the original question and added the model info. Commented Apr 14, 2014 at 18:08
  • definately try and do it my way, because then it opens you up to be able to do nice model binding using knockout.js, I insist quite strongly to look into knockout.js (just search), its fun and really helps separate out your code to make it so much more maintainable. Commented Apr 14, 2014 at 18:16

1 Answer 1

1

What you need to do is separate out what you want to do in C# and do that server side, then send through to the client side the code to be displayed.

For instance:

public class MyModel {
    public string JsonArray {get;set;}

}

public class MyController {

    public ActionResult MyView(List<items> someList) {
         // items will be x in this context, feel free to call it item :)
         var jsonString = JsonConvert.Serialize(someList.select(x => new {
             someValue = x.someValue
         }));

         return View(new MyModel { JsonArray = jsonString });
    }
}

JsonConvert is from the NewtonSoft library that is packaged in every MVC 4 project. It's so useful for passing JSON friendly data to the client side. You should only use the client side to display information, try and get the server side to process the data ready for client side, hence the MODEL, VIEW, CONTROLLER approach. View should have very little if no knowledge of server side things.

Services is a good way to do this. Dependency Injection, but these are more complicated, read something from Apress books.

In the client side:

@model {namespace}.MyModel
<script>
    var arrayToIterate = '@Html.Raw(Model.JsonArray)'

    // then do some JQuery or JavaScript iteration here:
<script>

Here is a jsfiddle of when you have got the data to the client side and you want to use knockout to bind it to a table. Really easy for display purposes

Sign up to request clarification or add additional context in comments.

1 Comment

@devlincarnate by any chance, did you use knockout? its so quick nd easy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.