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,470
  • 14
  • 27

3 Answers3

5

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

Dandy
  • 2,159
  • 13
  • 15
2

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

<div ng-init="init(isComplete: @Html.Raw(ViewBag.IsComplete))" />
Shyju
  • 206,216
  • 101
  • 402
  • 492
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,656
  • 6
  • 51
  • 80
  • 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