Html conditional compilation disabled in MVC C #
I wrote this function
<script type="text/javascript"> function saveDelivery() { alert("tttt") var model = @Html.Raw(Json.Encode(Model)); //errror $.ajax({ type: 'POST', url: '@Url.Action("SaveDelivery", "Business")', contentType: 'application/json; charset=utf-8', data: JSON.serialize(model), success: function (result) { }, error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); } }); } but there is an error on
var model = @Html.Raw(Json.Encode(Model)); says conditional compilation is turned off How to do this?
You can use the Html extension to output script tags. It will also help deal with Intellisense issues in Visual Studio.
public static class Extensions { public static IHtmlString BeginScript(this HtmlHelper htmlHelper) { return new HtmlString("<script type=\"text/javascript\">"); } public static IHtmlString EndScript(this HtmlHelper htmlHelper) { return new HtmlString("</script>"); } } And then, in your opinion:
@Html.BeginScript() // JavaScript... var model = @Html.Raw(Json.Encode(Model)); // More JavaScript... @Html.EndScript() NOTE. You need to add the namespace of your extension class to the <system.web.webPages.razor> element in web.config (the one that is in the views folder)
mvc 4 link is missing for Json.Encode
first add system.web.helper refrence
then right click on this refrence property and change Copy Locaal = false to true and run your code using json.Encode