Reputation: 2690
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("<script>");
scriptHtml.Append(@"var {0} = {{
id: 'someText',
title: '{1}',
$(document).ready(function () {{
$.function({0});
}});");
scriptHtml.Append("</script>");
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.
Upvotes: 1
Views: 601
Reputation: 2105
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
<script>
var @Model.Id = {{
id: 'someText',
title: '@Model.Title',
$(document).ready(function () {{
$.function(@Model.Id);
}});
</script>
//instantiate the model
var model = new MyScriptModel {Id="someid", Title="some title"};
//using your partial view
@Html.Partial("my_partial", model)
Upvotes: 1