1

I am curious how to handle setting nullable model information on an aspx page to a JavaScript variable. I am using MVC3 RC, and I am sure this is trivial and I am missing something.

Given this code (again, in my aspx view):

var myFloat = <%: Model.MyNullableFloat %>;

if SelectedAudience is null, what gets written to the page is:

var myFloat = ;

What I want to get written is:

var myFloat = null;

Currently, I have some ugly logic:

    var myFloat = null;
    <%
        if(Model.MyNullableFloat != null) {
    %>
            myFloat = <%: Model.AdGroup.MyNullableFloat %>;
    <%
        }
    %>

Any thoughts on a cleaner way?

Thanks

4 Answers 4

3

You can use a conditional operator

var myFloat = <%: Model.MyNullableFloat.HasValue
    ? Model.MyNullableFloat.Value.ToString() 
    : "null"%>;

Remember that both conditions need to return the same type so you'll have to ToString() the result if you want to return "null".

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

Comments

1

Use Ternary operator for a quick solution:

var myFloat = <%: Model.MyNullableFloat.HasValue ? Model.MyNullableFloat.Value : "null"  %>;

1 Comment

you'll need to ToString() the value otherwise that will throw an exception
1

It's not much better..!

<%= Model.MyNullableFloat.HasValue? Model.MyNullableFloat.ToString() : "null"%>;

or you could try an extension method

public static string ToStringVerboseNull(this float? myFloat)
{
    return myFloat.HasValue ? myFloat.ToString() : "null";
}

and then

<%= myFloat.ToStringVerboseNull()%>

Comments

1
var myFloat = <%= Model.MyNullableFloat != null ? Model.MyNullableFloat.ToString() : "null" %>;

You could also handle this in your Controller

Public Class MyModel {
  public string MyNullableFloatAsString { get; set; }
}

Public ActionResult Something () {
  MyModel MyControllerModel;

  MyControllerModel.MyNullableFloatAsString = Model.MyNullableFloat != null ? Model.MyNullableFloat.ToString() + ";" : "null;"

  //Return Model to view
}

Now in your View you can simply do this

var myFloat = <%= Model.MyNullableFloatAsString %>

1 Comment

don't you have to ToString() the nullable float?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.