Exact
Exact

Reputation: 269

ASP MVC 5 : How to pass Integer from controller to the view

I want to call a variable from the controller in my view in ASP MVC 5.

I tried using ViewBag but the variable get Null Value.

This is what I've tried :

Controller :

     SqlCommand command3 = new SqlCommand("select count (ClientId) from Client", con);
     con.Open();
     string c = command3.ExecuteScalar().ToString();
     con.Close();                  
     int cc = Convert.ToInt32(c);
     ViewBag.nbre = cc;

View :

  @model IList<Delivery.Models.Client>
  @for (int j=0; j < ViewBag.nbre; j++) {

Upvotes: 1

Views: 2455

Answers (2)

CodeGhost
CodeGhost

Reputation: 319

Well, first of all using the viewbag is [discouraged][1].

As you already send the list to the view, you can simply call the count action there rather than send it through the viewbag

Like so:

for(int j =0; j < @Model.Count(); j++) {

Upvotes: 1

C. Robin
C. Robin

Reputation: 31

At the top of your view use the following code

@model Int32

in your controller

public ActionResult Index()
{
   int mynumber = 5;
   return View(mynumber);
}

then use this in your view, should work no problem

@for(int j=0; j < @Model; j==) {

}

Upvotes: 2

Related Questions