0

In the MVC project I have an assignment:

ViewBag.SomeOne = "one";
ViewBag.SomeTwo = "two";

On the page, I'm displaying the first directly:

<div id="one">@ViewBag.SomeOne</div>

The other, isn't displayed at first. I've been instructed to create a jQuery expression that combines the two and creates a DIV element with them in it upon a click on the visible one. So I went:

<script type="text/javascript">
  $(document).ready(function () {
    $("#one").click(function () {
      var toghether = "";
      $("#both").append(together);
    }
  }
</script>

Now, the problem is that I can't find a nice way to access the value of ViewBag.One and can't find any way to access the value of ViewBag.Two.

I went cheating like this:

$("#one").text();

How can I make it better? And how can I access the other?

1 Answer 1

2

you can access ViewBag value from javascript :

var toghether = '@(ViewBag.SomeOne)' + ' @(ViewBag.SomeTwo)';

for example :

public ActionResult Index()
{
  ViewBag.SomeOne = "one";
  ViewBag.SomeTwo = "two";
}

in View :

@section JavaScript{
   <script type="text/javascript">
      $(document).ready(function () {
        $("#one").click(function () {
          var toghether = '@(ViewBag.SomeOne)' + ' @(ViewBag.SomeTwo)';
          $("#both").append(together);
        }
      }
  </script>
}
Sign up to request clarification or add additional context in comments.

2 Comments

Oh, this was nice. I always put in the script tag outside section. Didn't think of this.
it's because I defined section in my _Layout page, you can put your code outside of section.

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.