I'm writing a method that generating a javascript code and sending the razor view.
But razor view encoding this according to its head.Codes is below.
This is my method body, returning a mvchtmlstring:
StringBuilder scriptHtml = new StringBuilder();
scriptHtml.Append("");
scriptHtml.Append(@"var {0} = {{
id: 'someText',
title: '{1}',
$(document).ready(function () {{
$.function({0});
}});");
scriptHtml.Append("");
var output = string.Format(scriptHtml.ToString(), this.Id, this.Title);
return MvcHtmlString.Create(output);
So now, its output is :
@<script>var tlyPageGuide,,"direction":"Right"
Something like this growing with encoded.
That's what I want is the Razor should not change my code while cshtml is creating and I gotta get pure javascript code with rendered.
Note : I don't want to use Html.Raw() for the solution.I want to make this on server-side.
Talk1:
what do you mean "on server side"? All your Razor Views rendered on server side.
Talk2:
I mean, I don't want any additional Html.Raw() code in the view. I want to encode it on return MvcHtmlString.Create(output) or method body for example. By the way; Html.Raw() is working but I don't want to use it every time and every where when I'm invoking my method via Helper like this @Html.Raw(Html.MyHelper.MyMethod()).
Solutions1
Have you considered using partial view?
For instance: (this code may contain errors but you get the idea):
class MyScriptModel
{
public string Id {get;set;}
public string Title {get;set;}
}
//your partial view: my_partial.cshtml
@model MyScriptModel
//extracted from your string builder
var @Model.Id = {{
id: 'someText',
title: '@Model.Title',
$(document).ready(function () {{
$.function(@Model.Id);
}});
//instantiate the model
var model = new MyScriptModel {Id="someid", Title="some title"};
//using your partial view
@Html.Partial("my_partial", model)