2

I pass model with default values (Id = 0, CityId = null, IsPublished = false) from controller to view:

public class MyModel
{
    public int Id { get; set; }
    public int? CityId { get; set; }
    public bool IsPublished { get; set; }
}

And in view I assign values from model to variables in javascript - cityId should be in javascript type of bool and isPublished should be in javascript null or type of int:

<script>    
    var cityId = @Model.CityId; // value: False
    var isPublished = @Model.IsPublished; // value: ''
</script>

But I have errors:

  • For cityId: Uncaught ReferenceError: False is not defined
  • For isPublished: Uncaught SyntaxError: Unexpected token ;

What should I do ?

4
  • Have you checked what the actual output in the HTML is? For starters C# coerces false to 'False', so you'll have an issue with case sensitivity there Commented Jul 7, 2016 at 12:36
  • var cityId = @Html.Raw(Json.Encode(Model.CityId)) (ditto for IsPublished) Commented Jul 7, 2016 at 12:39
  • Are you sure your bool IsPublished is giving ''? And your int CityId giving 'False' ? Commented Jul 7, 2016 at 13:33
  • @Stephen Muecke thx - it works :) Commented Jul 7, 2016 at 13:37

3 Answers 3

4

You can use Json.Encode Method converts a data object to a string that is in the JavaScript Object Notation (JSON) format.

var settings = @Html.Raw(Json.Encode(Model))

Then it can used like

var cityId = settings.CityId; 
var isPublished = settings.IsPublished; 
Sign up to request clarification or add additional context in comments.

Comments

3

For the boolean, always lowercase it:

var isPublished = @Model.IsPublished.ToString().ToLowerInvariant(); 

For the nullable, check it has a value and give javascript something by default:

var cityId = @Model.CityId ?? "null"; 

2 Comments

var cityId = @Model.CityId ?? "null"; - it doesn't work :(
@MrChudz care to elaborate? You get any error message?
0

It's because your code is implicitly execute with ToString.

So C# bool.ToString() returns either True or False.

In Javascript, it's lowercase: true or false.

So you have to write it like this:

<script>    
    var cityId = @Model.CityId; // value: False
    var isPublished = @Model.IsPublished.ToString().ToLower(); // value: ''
</script>

Comments

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.