3

I have a controller:

public ActionResult Edit(int id) {
    ViewBag.IsComplete = false;
    return View(dbContext.Users.Where(user => user.Id == id))
}

and the corresponding view:

@model User

@{
    ViewBag.Title = "Edit User";
    Layout = "~/Views/Shared/_PopupLayout.cshtml";
}

<p>@ViewBag.IsComplete</p>

<div ng-init="init(isComplete: @ViewBag.IsComplete)" />

The first instance of ViewBag.IsComplete (in the <p> tag) emits the correct value. The second emits null. Can anyone tell me what is going on here and how to fix it so the second @ViewBag.IsComplete emits the same as the first?

DrewB
  • 1,503
  • 1
  • 14
  • 28

4 Answers4

6

Use @Html.Raw(ViewBag.IsComplete) in your ng-init binding.

Dandy
  • 2,177
  • 14
  • 16
2

Use @Html.Raw which returns html markup which is not encoded.

<div ng-init="init(isComplete: @Html.Raw(ViewBag.IsComplete))" />
Shyju
  • 214,206
  • 104
  • 411
  • 497
1

You need to convert the bool value to string, you can either use @Html.Raw() as suggested in other answers, or just do @ViewBag.IsComplete.ToString().

But, when you convert a bool value to string in C#, it will be converted to either "True" or "False", but Javascript doesn't recognize those as bool values. So, you'll have to convert it to lowercase as well. Here's what you need to do:

<div ng-init="init(isComplete: @ViewBag.IsComplete.ToString().ToLower())" />
ataravati
  • 8,891
  • 9
  • 57
  • 89
  • Thanks. I actually found that out almost immediately after I implemented Dandy's answer. My solution was to just set IsComplete to "true" or "false" and then use @HTml.Raw to write it out. It's only used to initialize an angularjs controller, so I don't care if it's a "real" boolean or not. – DrewB Nov 02 '15 at 16:08
0

In concept:

<div ng-init="init(isComplete: '@ViewBag.IsString')" />

Note the ViewBag.IsString, is replaced directly in the Html, So if it's a string ViewBag.IsString= "Mystring"

html is:

<div ng-init="init(isComplete: 'Mystring')" />

in your case :

<div ng-init="init(isComplete: true)" />  //might give error

try : <div ng-init="init(@ViewBag.IsComplete)" /> might not work since it replaces it with true, else pass string or json