0

I am new to MVC and trying from last 7 hours to pass value from viewBag to javascript function in MVC 5. I have a string variable

ViewBag.c1 = "0.30"

and i passed it to view and stored it as a hidden element

@Html.Hidden("Superman", (string)ViewBag.c1)

and then i want to access the value of this hidden element in following js function

function getValue1() {
return parseFloat(document.getElementById("Superman"));
}
1
  • 1
    The hidden input is not necessary. You can just use function getValue1() { return @Html.Raw(Json.Encode(ViewBag.c1)) } and the controller code should be ViewBag.c1 = 0.30F; is you want a number Commented May 4, 2018 at 7:30

3 Answers 3

4

@Html.Hidden("Superman", (string)ViewBag.c1)


function getValue1() {
  return parseFloat($("#Superman").val());
}

//or

function getValue1() {
  return parseFloat(document.getElementById("Superman").value);
}

Sign up to request clarification or add additional context in comments.

Comments

1
var c1Value = "@Html.Raw(ViewBag.c1)";

function getValue1() {
  return parseFloat(document.getElementById(c1Value).value);
}

Comments

0

You could simply store view-bag value in JavaScript variable like below.

<script> var yourValue = '@ViewBag.c1' </script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.