Search code examples
razor

How to Json.Encode a string and use it as Value for Hidden Input field?


Does anyone see why this controller/view code is rendering incorrectly?

Controller:

ViewBag.tempString = "some temp string";

...

Razor View:

<input id="tempJson" type="hidden" value="@Html.Raw(Json.Encode(ViewBag.tempString))" />

renders as:

<input id="tempJson" type="hidden" value some temp string"">

Solution

  • The value of @Html.Raw(Json.Encode(ViewBag.tempString)) is already a string. So try like this:

    value= @Html.Raw(Json.Encode(ViewBag.tempString))