Exitos
Exitos

Reputation: 29720

Whats the difference with this razor?

I have a view with the following razor...

foreach (var result in @Model.Results)
{
    if (result.Location != null && result.Location.Lat != null && result.Location.Long != null)
    {                   
        <script type="text/javascript" language="javascript">

            var MapDataObj = (function () {
                mapDataObj = new Object();
                mapDataObj.Lat = @result.Location.Lat;
                mapDataObj.Long = @result.Location.Long;
                mapDataObj.BasedInArea = 'True';
                SearchMapDataProperties.searchResultsArray.push(mapDataObj);
                return {

                };
            }());
        </script>
    }

But when I change it to...

foreach (var result in @Model.Results)
{
    if (result.Location != null && result.Location.Lat != null && result.Location.Long != null)
    {                   
        <script type="text/javascript" language="javascript">

            var MapDataObj = (function () {
                mapDataObj = new Object();
                mapDataObj.Lat = result.Location.Lat;
                mapDataObj.Long = result.Location.Long;
                mapDataObj.BasedInArea = 'True';
                SearchMapDataProperties.searchResultsArray.push(mapDataObj);
                return {

                };
            }());
        </script>
    }

(I have removed the '@' symbol from the result.Location object) I get a null reference exception on the result.Location.

I'm really confused about the difference. Its obviously still treating it as c# because I get a YSOD. I just cant fathom what the difference is...

Pete

Upvotes: 0

Views: 99

Answers (2)

Brad Christie
Brad Christie

Reputation: 101604

@result is referencing a view model (an object within the enumerable Model.Results being iterated through your foreach). When you remove the @ you're now trying to reference a JavaScript object called result (which is presumably undefined).

If you want this kind of control. you can use Newtonsoft's JSON library and serialize the model to result (something like:)

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

(Assuming you has a Json.Encode helper) which could make Model.Results look something like this after it's serialized in HTML:

var result = [
  {"Location":{"Lat":"0.00","Long":"0.00"}},
  {"Location":{"Lat":"0.00","Long":"0.00"}}
];

Ir, of course, the single instance for:

var result = @Html.Raw(Json.Encode(result));
// result = {"Location":{"Lat":"0.00","Long":"0.00"}}

Which now will work when referencing result without razor.

Upvotes: 2

Grant Thomas
Grant Thomas

Reputation: 45083

With Razor, using the @ prefix seems to handle null instances (presumably by returning an empty string) whereas in "C# proper" you don't get this safety mechanism, you'll have to check that Location is not null.

Upvotes: 0

Related Questions