Testing of variable content

Asked

Viewed 148 times

2

Using ASP.Net MVC and Angularjs I tested the contents of a view thus:

$scope.estado.ldRedeBasica =  @(Model.ldRedeBasica == null ? "[]" : Html.Raw(Model.ldRedeBasica));

Only it returned the following error:

Compiler Error Message: CS0173: The conditional expression type cannot be determined because there is no implicit conversion between 'string' and 'System.Web.Ihtmlstring'

The interesting thing is that in another part of the code works:

$scope.ViewBag.Impostos = @(ViewBag.Impostos == null ? "[]" : Html.Raw(ViewBag.Impostos));

How to get around this problem?

1 answer

1


Do so:

$scope.estado.ldRedeBasica =  @(Model.ldRedeBasica == null
                                ? new MvcHtmlString("[]") // ou poderia ser `Html.Raw("[]")`
                                : Html.Raw(Model.ldRedeBasica));

    Documentation of Mvchtmlstring

The error occurs because Html.Raw does not return string, but rather an implementation of the kind IHtmlString.

Imagine the situation:

var x = (condicao == true) ? "string" : 32784;

What kind of x?... impossible to say. The error you have is of the same kind as above.

To be able to determine the type of a condition using ternary operator, it is necessary that one of the expressions is convertible to the type of the other expression... which is not the case.

  • nor of string for IHtmlString
  • nor of IHtmlString for string

Now, to know why the other code works, then it will take a deeper investigation... not being possible to say just with what was put.

  • Thank you for the answer! Really did not return the original error. Now it is returning Uncaught Syntaxerror: Unexpected token ; in the console the code is so: $scope.estado.ldRedeBasica = ;.

  • What kind is Model.ldRedeBasica?

  • If it is an array or list, you must serialize the object to JSON before using Html.Raw in it.

  • I resolved so: $scope.estado.ldRedeBasica = @(String.IsNullOrEmpty(Model.ldRedeBasica) ? Html.Raw("[]") : Html.Raw(Model.ldRedeBasica));. Thanks for the help.

  • From what I said, you can tell the guy’s a string. Use String.IsNullOrWhiteSpace instead, to rule out the possibility of white spaces.

  • It was barely String even! I’ll make the change. Thanks again!

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.