Use Viewbag as counter

Asked

Viewed 399 times

2

Is there any way I can use the ViewBag as an accountant?

WHAT I NEED?

I’m making phone registrations. When I add a new phone, I send my View for my Controller and he returns me to PartialView of my Inputs.

Needed an accountant, 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>

where my difficulty comes in, an accountant in MVC

CALLED AJAX

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

  • Have you tried to create a variable within cshtml to receive Viewbag and counter that variable?

  • Post as you are calling the partialView with the inputs. I think you must be using ajax.

  • Yes @Randrade on my call Ajax I send him to Controller and he returns to PartialView

  • Add your ajax code too

  • ready @Randrade changed the question with the code Ajax

  • That counter you need for what? Will send it to some controller in the end?

  • not @Randrade only integration with jQuery , for example, exclude such an element from a div, several id

Show 3 more comments

2 answers

2


You use only the ViewBag in your action will not have the expected result. What I advise is to send the number of the counter per 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 its partial to accomplish what it needs.

0

Actually this is the way well wrong to perform a ratio of cardinality 1 to N in a View. The correct way is not to "count" the number of phones. The correct way is to generate as many phone elements as you want, and the Model Binder be able to count how many elements have been generated.

This can be done manually, but the right way to do it is by using the Nuget package called Begincollectionitem. We have already fully responded on this package. If you need me, I’ll expand the example for phone registration, but I don’t think you need. Here I teach logic in Javascript to create phone blocks. Here is the full example.

  • thanks for the reply, but I’m not doing for the Model Binder to count how many was generated, just to specify some integrations in my View, thanks in advance

Browser other questions tagged

You are not signed in. Login or sign up in order to post.