ASP.NET MVC using ViewData in javascript

前端 未结 2 1017
广开言路
广开言路 2020-12-05 03:04

I am currently building a website in ASP.NET MVC. I am trying to access ViewData in javascript.

Is there any way that I can access a string value using javascript in

相关标签:
2条回答
  • 2020-12-05 03:18

    Like this (Razor):

    var str = @Html.Raw(Json.Encode(ViewData["Text"]));
    

    or (WebForms), using the JavaScriptSerializer (and after importing theproper namespace to your webform - System.Web.Script.Serialization):

    var str = <%= new JavaScriptSerializer().Serialize(ViewData["Text"])) %>;
    

    And please don't use ViewData in an ASP.NET MVC application. Use view models and strongly typed views so that your code looks like this:

    var str = <%= new JavaScriptSerializer().Serialize(Model.Text) %>;
    

    This technique is even cooler as now you can JSON serialize the entire view model:

    var model = <%= new JavaScriptSerializer().Serialize(Model) %>;
    var str = model.Text;
    
    0 讨论(0)
  • 2020-12-05 03:30

    That should be:

    var str = '<%= ViewData["Text"] %>';
    
    0 讨论(0)
提交回复
热议问题