How to get to Model or Viewbag Variables in a Scri

2019-02-03 05:01发布

问题:

Vs'12 asp.net C# MVC4 - Int.Appl.Template EF Code First

Here is my very simple Script

<script class="TractsScript">

     $('#Add').click(function (e) {

         var val = @ViewBag.ForSection;
         alert(val);

     });
</script>

As per example I am wanting to simply set a variable in my script or USE a Viewbag. or Model.

I haven't been able to find an answer in any of the following forums: StckTrace1,StackTraceBetterAnswer

Other Things i have tried:

var model = @Html.Raw(Json.Encode(Model))
alert(model.Sections);
alert(@ViewBag.ForSection);

回答1:

You can do this way, providing Json or Any other variable:

1) For exemple, in the controller, you can use Json.NET to provide Json to the ViewBag:

ViewBag.Number = 10;
ViewBag.FooObj = JsonConvert.SerializeObject(new Foo { Text = "Im a foo." });

2) In the View, put the script like this at the bottom of the page.

<script type="text/javascript">
    var number = parseInt(@ViewBag.Number); //Accessing the number from the ViewBag
    alert("Number is: " + number);
    var model = @Html.Raw(@ViewBag.FooObj); //Accessing the Json Object from ViewBag
    alert("Text is: " + model.Text);
</script> 


回答2:

What you have should work. It depends on the type of data you are setting i.e. if it's a string value you need to make sure it's in quotes e.g.

var val = '@ViewBag.ForSection';

If it's an integer you need to parse it as one i.e.

var val = parseInt(@ViewBag.ForSection);


回答3:

try this method

<script type="text/javascript">

    function set(value) {
        return value;
    }

    alert(set(@Html.Raw(Json.Encode(Model.Message)))); // Message set from controller
    alert(set(@Html.Raw(Json.Encode(ViewBag.UrMessage))));

</script>

Thanks



回答4:

Use single quotation marks ('):

var val = '@ViewBag.ForSection';
alert(val);


回答5:

When you're doing this

var model = @Html.Raw(Json.Encode(Model));

You're probably getting a JSON string, and not a JavaScript object.

You need to parse it in to an object:

var model = JSON.parse(model); //or $.parseJSON() since if jQuery is included
console.log(model.Sections);