Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net Razor alternative to PHP echo

I'm new to .net MVC and Razor engine but I have been using PHP for a long time. I'm trying to do this PHP code in Razor:

var data = [
<?php for ($i = 0; $i < 50; ++$i) { 
  echo '[' . $i . ',' . sin($i) . ']';
  if ($i != 49)
    echo ',';
?>
],

I managed to do it using this, but it looks bad and complex for something so simple

var data = [
  @for(int i = 0; i < 50; ++i) {  
<text>[</text>@i<text>,</text>@Math.Sin(i)<text>]</text>if (i != 49) {<text>,</text>}
  } 
];

The problem is that [, ] and , are confused with Razor syntax and gives syntax errors, so I had to wrap them on <text> tags.

Is there a simpler/nicer way to do this? Maybe something like the PHP echo.

Thanks.

like image 627
Sheol Avatar asked Oct 04 '12 16:10

Sheol


2 Answers

A gerenal equivalent of echo in MVC cshtml might be: @Html.Raw("SomeStringDirectlyInsideTheBrowserPageHTMLCode")

This renders the (dynamic) string at its position where '<' and '>' no need to be HTML-coded. For example @Html.Raw(String.Format("<div class=\"{0}\" style=\"{1}\">", myclass, mystyle)) works fine.

Note that the HTML tags rendered by @Html.Raw(MyString) cannot be checked by the compiler. I mean: @Html.Raw("<div ....>") cannot be closed by mere </div> because you will get an error (<div ....> is not detected by the compiler) so you must close the tag with @Html.Raw("</div>")

P.S.
In some cases this doesn't work (for example it fails within DevExpress) - use ViewContext.Writer.Write() or ViewContext.Writer.WriteLine() instead.

like image 140
KurvaBG Avatar answered Sep 20 '22 18:09

KurvaBG


Use this:

@String.Format("[{0},{1}]", i, Math.Sin(i))

And for comma you can use String.Join() if you create array (String.Join Method )

like image 27
webdeveloper Avatar answered Sep 20 '22 18:09

webdeveloper