Use ViewBag as counter

2

How can I use ViewBag as counter?

WHAT DO I NEED?

I'm making phone numbers. When I add a new phone, I send my View to my Controller and it returns me to PartialView of my Inputs .

I needed a counter, how many times I added the phone, to reference the Input , for example, I added a phone:

<div class="telefone1"></div>

I added another

<div class="telefone2"></div>

Here is where my difficulty comes in, a counter in MVC

AJAX CALL

    $.ajax({
    url: '/Controller/AddTelefone',
    success: function (partialView) {
        $('#div').append(partialView);
    }
    });

MY CONTROLLER

    //variavel global
    public int count = 0;

    public ActionResult AddTelefone()
    {
        ViewBag.count = count + 1;
        return PartialView("partialview");
    }

MY VIEW

@{
   var thing = ViewBag.count;
}
@Html.Raw(thing)

ERROR!

My ViewBag.count is always with the value: 1 .

    
asked by anonymous 08.12.2015 / 13:36

2 answers

2

Only using ViewBag in your action will not have the expected result. What I advise is to send the quantity of the counter by parameter via Ajax , and return the value.

Your Action would look like this:

public ActionResult AddTelefone(int contador)
    {
        ViewBag.count = contador + 1;
        return PartialView("partialview");
    }

With this, just return the value of ViewBag.Count in your partial to accomplish what you need.

    
08.12.2015 / 14:29
0

This is actually the wrong way to perform a cardinality relation 1 to N in a View . The correct way is not you "count" the number of phones. The right way is to generate as many phone elements as you want, and Model Binder has the ability to count how many elements were generated.

This can be done manually, but the correct way to do this is by using the NuGet package called BeginCollectionItem . We have already answered extensively about this package . If you need, expando the example to register phones, but do not think you need to. Here I teach logic in JavaScript to create blocks of phones . Here is the full example .

    
08.12.2015 / 15:26