-1

I`m working on a MVC project in C#, and I tried to write this in the VIEW part:

@foreach (var item in Model)
                        {
                                string str = "{ y: ";
                                str = str + item.count;
                                str = str + ", lable: ";
                                str = str + "\"" + item.agency_name + "\"";
                                str = str + "}, ";

                                @Html.Raw(str)

                        }

As you can see this is part of HTML that is in my view, and I would like to know how to omit the last comma. The problem is that I don`t know how to iterate the model item without using foreach. I also tried to define a counter, but could not manage to define a counter variable outside of this scope.

Yamit Orr
  • 9
  • 1
  • 2
  • 3
    As we can see you are generating potentially invalid JSON. Please save yourself some trouble and use existing ways to build it. Correctly writing out JSON is tricky aleady without string manipulation, especially if you are doing it as part of mixed HTML/JavaScript context. – Alexei Levenkov May 25 '16 at 21:38
  • It is simple you just remove your comma from `str = str + "}, ";` – techspider May 25 '16 at 21:39
  • @techspider it will JSON even more invalid - notice that OP have list of objects - hence need to separate all items in array with comma. – Alexei Levenkov May 25 '16 at 21:40
  • @AlexeiLevenkov - right, I didn't pay attention to it!! I wonder why he needs to loop through to generate JSON!! OP may need to go back to books – techspider May 25 '16 at 21:42
  • What is it that your really trying to do here? Why are you not returning a `JsonResult` from the controller? What is the purpose of just displaying json in the view? –  May 26 '16 at 00:02

1 Answers1

2

It seems to me you are building a json-response in your view. While possible, it isn't very easy, so maybe you would like to consider returning json directly from the controller:

public ActionResult Method()
{
    return Json(new {y= item.Count, label=item.Agency.Name});
}

As described in the answer here: ASP.NET MVC controller actions that return JSON or partial html

My apologies if I misinterpret your question.

Community
  • 1
  • 1
faester
  • 14,886
  • 5
  • 45
  • 56