从Javascript访问MVC的模型属性

时间:2021-10-05 16:54:05

I have the following model which is wrapped in my view model

我有下面的模型,它被包装在我的视图模型中

public class FloorPlanSettingsModel
{
    public int Id { get; set; }
    public int? MainFloorPlanId { get; set; }
    public string ImageDirectory { get; set; }
    public string ThumbnailDirectory { get; set; }
    public string IconsDirectory { get; set; }
}

How do I access one of the above properties from Javascript?

如何从Javascript访问上述属性之一?

I tried this, but I got "undefined"

我试过了,但是没有定义

var floorplanSettings = "@Model.FloorPlanSettings";
alert(floorplanSettings.IconsDirectory);

5 个解决方案

#1


157  

You could take your entire server-side model and turn it into a Javascript object by doing the following:

您可以将整个服务器端模型转换为Javascript对象,方法如下:

var model = @Html.Raw(Json.Encode(Model));

In your case if you just want the FloorPlanSettings object, simply pass the Encode method that property:

在您的情况下,如果您只想要FloorPlanSettings对象,只需传递属性的Encode方法:

var floorplanSettings = @Html.Raw(Json.Encode(Model.FloorPlanSettings));

#2


65  

Contents of the Answer

回答的内容

1) How to access Model data in Javascript/Jquery code block in .cshtml file

1)如何在.cshtml文件中访问Javascript/Jquery代码块中的模型数据

2) How to access Model data in Javascript/Jquery code block in .js file

2)如何在.js文件中访问Javascript/Jquery代码块中的模型数据

How to access Model data in Javascript/Jquery code block in .cshtml file

There are two types of c# variable (Model) assignments to JavaScript variable.

有两种类型的c#变量(模型)分配给JavaScript变量。

  1. Property assignment - Basic datatypes like int, string, DateTime (ex: Model.Name)
  2. 属性分配——基本数据类型,如int、string、DateTime (ex: Model.Name)
  3. Object assignment - Custom or inbuilt classes (ex: Model, Model.UserSettingsObj)
  4. 对象分配——自定义或内建类(例如:Model. usersettingsobj)

Lets look into the details of these two assignments.

让我们来看看这两个作业的细节。

For the rest of the answer lets consider the below AppUser Model as an example.

对于其余的答案,让我们以下面的AppUser模型为例。

public class AppUser
{
    public string Name { get; set; }
    public bool IsAuthenticated { get; set; }
    public DateTime LoginDateTime { get; set; }
    public int Age { get; set; }
    public string UserIconHTML { get; set; }
}

And the values we assign this Model are

我们分配这个模型的值是。

AppUser appUser = new AppUser
{
    Name = "Raj",
    IsAuthenticated = true,
    LoginDateTime = DateTime.Now,
    Age = 26,
    UserIconHTML = "<i class='fa fa-users'></i>"
};

Property assignment

Lets use different syntax for assignment and observe the results.

让我们使用不同的语法分配和观察结果。

1) Without wrapping property assignment in quotes.

1)不使用引号括起属性赋值。

var Name = @Model.Name;  
var Age = @Model.Age;
var LoginTime = @Model.LoginDateTime; 
var IsAuthenticated = @Model.IsAuthenticated;   
var IconHtml = @Model.UserIconHTML;  

从Javascript访问MVC的模型属性

As you can see there are couple of errors, Raj and True is considered to be javascript variables and since they dont exist its an variable undefined error. Where as for the dateTime varialble the error is unexpected number numbers cannot have special characters, The HTML tags are converted into its entity names so that the browser doesn't mix up your values and the HTML markup.

正如您所看到的,有两个错误,Raj和True被认为是javascript变量,由于它们不存在,所以它是一个变量未定义的错误。对于dateTime的变量,错误是无法预料的数字不能有特殊的字符,HTML标记被转换为它的实体名称,这样浏览器就不会混淆您的值和HTML标记。

2) Wrapping property assignment in Quotes.

2)用引号括起属性赋值。

var Name = '@Model.Name';
var Age = '@Model.Age';
var LoginTime = '@Model.LoginDateTime';
var IsAuthenticated = '@Model.IsAuthenticated';
var IconHtml = '@Model.UserIconHTML'; 

从Javascript访问MVC的模型属性

The results are valid, So wrapping the property assignment in quotes gives us valid syntax. But note that the Number Age is now a string, So if you dont want that we can just remove the quotes and it will be rendered as a number type.

结果是有效的,所以用引号括起属性赋值可以得到有效的语法。但是请注意,Number Age现在是一个字符串,所以如果您不想这样,我们可以删除引号,它将被呈现为数字类型。

3) Using @Html.Raw but without wrapping it in quotes

3)使用@Html。生词,但不要用引号括起来。

 var Name = @Html.Raw(Model.Name);
 var Age = @Html.Raw(Model.Age);
 var LoginTime = @Html.Raw(Model.LoginDateTime);
 var IsAuthenticated = @Html.Raw(Model.IsAuthenticated);
 var IconHtml = @Html.Raw(Model.UserIconHTML);

从Javascript访问MVC的模型属性

The results are similar to our test case 1. However using @Html.Raw()on the HTML string did show us some change. The HTML is retained without changing to its entity names.

结果与我们的测试用例1相似。但是在HTML字符串上使用@Html.Raw()确实显示了一些变化。保留HTML而不更改其实体名称。

From the docs Html.Raw()

从文档Html.Raw()

Wraps HTML markup in an HtmlString instance so that it is interpreted as HTML markup.

在HTML字符串实例中包装HTML标记,以便将其解释为HTML标记。

But still we have errors in other lines.

但是我们在其他行还是有错误。

4) Using @Html.Raw and also wrapping it within quotes

4)使用@Html。原始的,也用引号括起来

var Name ='@Html.Raw(Model.Name)';
var Age = '@Html.Raw(Model.Age)';
var LoginTime = '@Html.Raw(Model.LoginDateTime)';
var IsAuthenticated = '@Html.Raw(Model.IsAuthenticated)';
var IconHtml = '@Html.Raw(Model.UserIconHTML)';

从Javascript访问MVC的模型属性

The results are good with all types. But our HTML data is now broken and this will break the scripts. The issue is because we are using single quotes ' to wrap the the data and even the data has single quotes.

所有类型的结果都很好。但是我们的HTML数据现在被破坏了,这将破坏脚本。问题是,我们使用单引号来包装数据,甚至数据也有单引号。

We can overcome this issue with 2 approaches.

我们可以用两种方法来解决这个问题。

1) use double quotes " " to wrap the HTML part. As the inner data has only single quotes. (Be sure that after wrapping with double quotes there are no " within the data too)

1)使用双引号“”来包装HTML部分。因为内部数据只有一个引号。(请确保在使用双引号之后,在数据中也没有)

  var IconHtml = "@Html.Raw(Model.UserIconHTML)";

2) Escape the character meaning in your server side code. Like

2)转义服务器端代码中的字符含义。就像

  UserIconHTML = "<i class=\"fa fa-users\"></i>"

Conclusion of property assignment

结论的财产分配

  • Use quotes for non numeric dataType.
  • 对非数字数据类型使用引号。
  • Do Not use quotes for numeric dataType.
  • 不要对数字数据类型使用引号。
  • Use Html.Raw to interpret your HTML data as is.
  • 使用Html。原始地解释HTML数据。
  • Take care of your HTML data to either escape the quotes meaning in server side, Or use a different quote than in data during assignment to javascript variable.
  • 注意HTML数据,以便在服务器端转义引号的含义,或者在向javascript变量赋值时使用与数据不同的引号。

Object assignment

Lets use different syntax for assignment and observe the results.

让我们使用不同的语法分配和观察结果。

1) Without wrapping object assignment in quotes.

1)不使用引号括起对象赋值。

  var userObj = @Model; 

从Javascript访问MVC的模型属性

When you assign a c# object to javascript variable the value of the .ToString() of that oject will be assigned. Hence the above result.

当您向javascript变量分配c#对象时,该对象的. tostring()的值将被分配。因此上述的结果。

2 Wrapping object assignment in quotes

用引号括住对象赋值

var userObj = '@Model'; 

从Javascript访问MVC的模型属性

3) Using Html.Raw without quotes.

3)使用Html。生没有引号。

   var userObj = @Html.Raw(Model); 

从Javascript访问MVC的模型属性

4) Using Html.Raw along with quotes

4)使用Html。生一起报价

   var userObj = '@Html.Raw(Model)'; 

从Javascript访问MVC的模型属性

The Html.Raw was of no much use for us while assigning a object to variable.

Html。在为变量分配对象时,Raw对我们来说没什么用。

5) Using Json.Encode() without quotes

5)使用Json.Encode()不带引号

var userObj = @Json.Encode(Model); 

//result is like
var userObj = {&quot;Name&quot;:&quot;Raj&quot;,
               &quot;IsAuthenticated&quot;:true,
               &quot;LoginDateTime&quot;:&quot;\/Date(1482572875150)\/&quot;,
               &quot;Age&quot;:26,
               &quot;UserIconHTML&quot;:&quot;\u003ci class=\&quot;fa fa-users\&quot;\u003e\u003c/i\u003e&quot;
              };

We do see some change, We see our Model is being interpreted as a object. But we have those special characters changed into entity names. Also wrapping the above syntax in quotes is of no much use. We simply get the same result within quotes.

我们确实看到了一些变化,我们看到我们的模型被解释为一个对象。但是我们把这些特殊的字符变成了实体名。同样,用引号括住上面的语法也没什么用。我们只是在引号中得到相同的结果。

From the docs of Json.Encode()

从Json.Encode()文档中

Converts a data object to a string that is in the JavaScript Object Notation (JSON) format.

将数据对象转换为JavaScript对象表示法(JSON)格式的字符串。

As you have already encountered this entity Name issue with property assignment and if you remember we overcame it with the use of Html.Raw. So lets try that out. Lets combine Html.Raw and Json.Encode

正如您已经遇到了属性赋值的实体名称问题,如果您还记得我们使用Html.Raw克服了这个问题。我们来试试。结合Html。生和Json.Encode

6) Using Html.Raw and Json.Encode without quotes.

6)使用Html。生和Json。编码没有引号。

var userObj = @Html.Raw(Json.Encode(Model));

Result is a valid Javascript Object

结果是一个有效的Javascript对象

 var userObj = {"Name":"Raj",
     "IsAuthenticated":true,
     "LoginDateTime":"\/Date(1482573224421)\/",
     "Age":26,
     "UserIconHTML":"\u003ci class=\"fa fa-users\"\u003e\u003c/i\u003e"
 };

从Javascript访问MVC的模型属性

7) Using Html.Raw and Json.Encode within quotes.

7)使用Html。生和Json。编码在引号内。

var userObj = '@Html.Raw(Json.Encode(Model))';

从Javascript访问MVC的模型属性

As you see wrapping with quotes gives us a JSON data

如您所见,用引号括起来会得到JSON数据

Conslusion on Object assignment

Conslusion对象赋值

  • Use Html.Raw and Json.Encode in combintaion to assign your object to javascript variable as JavaScript object.
  • 使用Html。生和Json。使用梳状编码将对象作为javascript对象分配给javascript变量。
  • Use Html.Raw and Json.Encode also wrap it within quotes to get a JSON
  • 使用Html。生和Json。Encode还将其封装在引号中以获取JSON

Note: If you have observed the DataTime data format is not right. This is because as said earlier Converts a data object to a string that is in the JavaScript Object Notation (JSON) format and JSON does not contain a date type. Other options to fix this is to add another line of code to handle this type alone using javascipt Date() object

注意:如果您观察到数据格式不正确。这是因为如前所述,将数据对象转换为JavaScript对象表示法(JSON)格式的字符串,而JSON不包含日期类型。解决此问题的其他选项是添加另一行代码,使用javascipt Date()对象单独处理此类型

var userObj.LoginDateTime = new Date('@Html.Raw(Model.LoginDateTime)'); 
//without Json.Encode


How to access Model data in Javascript/Jquery code block in .js file

Razor syntax has no meaning in .js file and hence we cannot directly use our Model insisde a .js file. However there is a workaround.

Razor语法在.js文件中没有任何意义,因此我们不能直接在.js文件中使用我们的模型。然而,有一个变通的办法。

1) Solution is using javascript Global variables.

1)解决方案是使用javascript全局变量。

We have to assign the value to a global scoped javascipt variable and then use this variable within all code block of your .cshtml and .js files. So the syntax would be

我们必须将值分配给全局作用域的javascipt变量,然后在.cshtml和.js文件的所有代码块中使用该变量。语法是

<script type="text/javascript">
  var userObj = @Html.Raw(Json.Encode(Model)); //For javascript object
  var userJsonObj = '@Html.Raw(Json.Encode(Model))'; //For json data
</script>

With this in place we can use the variables userObj and userJsonObj as and when needed.

在适当的位置上,我们可以在需要时使用userObj和userJsonObj变量。

Note: I personally dont suggest using global variables as it gets very hard for maintainance. However if you have no other option then you can use it with having a proper naming convention .. something like userAppDetails_global.

注意:我个人不建议使用全局变量,因为这样很难维护。但是,如果您没有其他选择,那么您可以使用它与一个合适的命名约定。就像userAppDetails_global。

2) Using function() or closure Wrap all the code that is dependent on the model data in a function. And then execute this function from the .cshtml file .

2)使用函数()或闭包来包装所有依赖于函数中模型数据的代码。然后从.cshtml文件执行此函数。

external.js

external.js

 function userDataDependent(userObj){
  //.... related code
 }

.cshtml file

.cshtml文件

 <script type="text/javascript">
  userDataDependent(@Html.Raw(Json.Encode(Model))); //execute the function     
</script>

Note: Your external file must be referenced prior to the above script. Else the userDataDependent function is undefined.

注意:您的外部文件必须在上述脚本之前被引用。另外,userDataDependent函数没有定义。

Also note that the function must be in global scope too. So either solution we have to deal with global scoped players.

还要注意,函数也必须在全局范围内。所以无论哪种解决方案,我们都必须与全球范围内的参与者打交道。

#3


17  

try this: (you missed the single quotes)

试试这个:(你错过了单引号)

var floorplanSettings = '@Html.Raw(Json.Encode(Model.FloorPlanSettings))';

#4


3  

Wrapping the model property around parens worked for me. You still get the same issue with Visual Studio complaining about the semi-colon, but it works.

将模型属性包装在parens上对我很有用。您仍然会遇到Visual Studio抱怨分号的问题,但是它是有效的。

var closedStatusId = @(Model.ClosedStatusId);

#5


0  

If "ReferenceError: Model is not defined" error is raised, then you might try to use the following method:

如果出现“ReferenceError: Model未定义”错误,您可以尝试使用以下方法:

$(document).ready(function () {

    @{  var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
         var json = serializer.Serialize(Model);
    }

    var model = @Html.Raw(json);
    if(model != null && @Html.Raw(json) != "undefined")
    {
        var id= model.Id;
        var mainFloorPlanId = model.MainFloorPlanId ;
        var imageDirectory = model.ImageDirectory ;
        var iconsDirectory = model.IconsDirectory ;
    }
});

Hope this helps...

希望这有助于……

#1


157  

You could take your entire server-side model and turn it into a Javascript object by doing the following:

您可以将整个服务器端模型转换为Javascript对象,方法如下:

var model = @Html.Raw(Json.Encode(Model));

In your case if you just want the FloorPlanSettings object, simply pass the Encode method that property:

在您的情况下,如果您只想要FloorPlanSettings对象,只需传递属性的Encode方法:

var floorplanSettings = @Html.Raw(Json.Encode(Model.FloorPlanSettings));

#2


65  

Contents of the Answer

回答的内容

1) How to access Model data in Javascript/Jquery code block in .cshtml file

1)如何在.cshtml文件中访问Javascript/Jquery代码块中的模型数据

2) How to access Model data in Javascript/Jquery code block in .js file

2)如何在.js文件中访问Javascript/Jquery代码块中的模型数据

How to access Model data in Javascript/Jquery code block in .cshtml file

There are two types of c# variable (Model) assignments to JavaScript variable.

有两种类型的c#变量(模型)分配给JavaScript变量。

  1. Property assignment - Basic datatypes like int, string, DateTime (ex: Model.Name)
  2. 属性分配——基本数据类型,如int、string、DateTime (ex: Model.Name)
  3. Object assignment - Custom or inbuilt classes (ex: Model, Model.UserSettingsObj)
  4. 对象分配——自定义或内建类(例如:Model. usersettingsobj)

Lets look into the details of these two assignments.

让我们来看看这两个作业的细节。

For the rest of the answer lets consider the below AppUser Model as an example.

对于其余的答案,让我们以下面的AppUser模型为例。

public class AppUser
{
    public string Name { get; set; }
    public bool IsAuthenticated { get; set; }
    public DateTime LoginDateTime { get; set; }
    public int Age { get; set; }
    public string UserIconHTML { get; set; }
}

And the values we assign this Model are

我们分配这个模型的值是。

AppUser appUser = new AppUser
{
    Name = "Raj",
    IsAuthenticated = true,
    LoginDateTime = DateTime.Now,
    Age = 26,
    UserIconHTML = "<i class='fa fa-users'></i>"
};

Property assignment

Lets use different syntax for assignment and observe the results.

让我们使用不同的语法分配和观察结果。

1) Without wrapping property assignment in quotes.

1)不使用引号括起属性赋值。

var Name = @Model.Name;  
var Age = @Model.Age;
var LoginTime = @Model.LoginDateTime; 
var IsAuthenticated = @Model.IsAuthenticated;   
var IconHtml = @Model.UserIconHTML;  

从Javascript访问MVC的模型属性

As you can see there are couple of errors, Raj and True is considered to be javascript variables and since they dont exist its an variable undefined error. Where as for the dateTime varialble the error is unexpected number numbers cannot have special characters, The HTML tags are converted into its entity names so that the browser doesn't mix up your values and the HTML markup.

正如您所看到的,有两个错误,Raj和True被认为是javascript变量,由于它们不存在,所以它是一个变量未定义的错误。对于dateTime的变量,错误是无法预料的数字不能有特殊的字符,HTML标记被转换为它的实体名称,这样浏览器就不会混淆您的值和HTML标记。

2) Wrapping property assignment in Quotes.

2)用引号括起属性赋值。

var Name = '@Model.Name';
var Age = '@Model.Age';
var LoginTime = '@Model.LoginDateTime';
var IsAuthenticated = '@Model.IsAuthenticated';
var IconHtml = '@Model.UserIconHTML'; 

从Javascript访问MVC的模型属性

The results are valid, So wrapping the property assignment in quotes gives us valid syntax. But note that the Number Age is now a string, So if you dont want that we can just remove the quotes and it will be rendered as a number type.

结果是有效的,所以用引号括起属性赋值可以得到有效的语法。但是请注意,Number Age现在是一个字符串,所以如果您不想这样,我们可以删除引号,它将被呈现为数字类型。

3) Using @Html.Raw but without wrapping it in quotes

3)使用@Html。生词,但不要用引号括起来。

 var Name = @Html.Raw(Model.Name);
 var Age = @Html.Raw(Model.Age);
 var LoginTime = @Html.Raw(Model.LoginDateTime);
 var IsAuthenticated = @Html.Raw(Model.IsAuthenticated);
 var IconHtml = @Html.Raw(Model.UserIconHTML);

从Javascript访问MVC的模型属性

The results are similar to our test case 1. However using @Html.Raw()on the HTML string did show us some change. The HTML is retained without changing to its entity names.

结果与我们的测试用例1相似。但是在HTML字符串上使用@Html.Raw()确实显示了一些变化。保留HTML而不更改其实体名称。

From the docs Html.Raw()

从文档Html.Raw()

Wraps HTML markup in an HtmlString instance so that it is interpreted as HTML markup.

在HTML字符串实例中包装HTML标记,以便将其解释为HTML标记。

But still we have errors in other lines.

但是我们在其他行还是有错误。

4) Using @Html.Raw and also wrapping it within quotes

4)使用@Html。原始的,也用引号括起来

var Name ='@Html.Raw(Model.Name)';
var Age = '@Html.Raw(Model.Age)';
var LoginTime = '@Html.Raw(Model.LoginDateTime)';
var IsAuthenticated = '@Html.Raw(Model.IsAuthenticated)';
var IconHtml = '@Html.Raw(Model.UserIconHTML)';

从Javascript访问MVC的模型属性

The results are good with all types. But our HTML data is now broken and this will break the scripts. The issue is because we are using single quotes ' to wrap the the data and even the data has single quotes.

所有类型的结果都很好。但是我们的HTML数据现在被破坏了,这将破坏脚本。问题是,我们使用单引号来包装数据,甚至数据也有单引号。

We can overcome this issue with 2 approaches.

我们可以用两种方法来解决这个问题。

1) use double quotes " " to wrap the HTML part. As the inner data has only single quotes. (Be sure that after wrapping with double quotes there are no " within the data too)

1)使用双引号“”来包装HTML部分。因为内部数据只有一个引号。(请确保在使用双引号之后,在数据中也没有)

  var IconHtml = "@Html.Raw(Model.UserIconHTML)";

2) Escape the character meaning in your server side code. Like

2)转义服务器端代码中的字符含义。就像

  UserIconHTML = "<i class=\"fa fa-users\"></i>"

Conclusion of property assignment

结论的财产分配

  • Use quotes for non numeric dataType.
  • 对非数字数据类型使用引号。
  • Do Not use quotes for numeric dataType.
  • 不要对数字数据类型使用引号。
  • Use Html.Raw to interpret your HTML data as is.
  • 使用Html。原始地解释HTML数据。
  • Take care of your HTML data to either escape the quotes meaning in server side, Or use a different quote than in data during assignment to javascript variable.
  • 注意HTML数据,以便在服务器端转义引号的含义,或者在向javascript变量赋值时使用与数据不同的引号。

Object assignment

Lets use different syntax for assignment and observe the results.

让我们使用不同的语法分配和观察结果。

1) Without wrapping object assignment in quotes.

1)不使用引号括起对象赋值。

  var userObj = @Model; 

从Javascript访问MVC的模型属性

When you assign a c# object to javascript variable the value of the .ToString() of that oject will be assigned. Hence the above result.

当您向javascript变量分配c#对象时,该对象的. tostring()的值将被分配。因此上述的结果。

2 Wrapping object assignment in quotes

用引号括住对象赋值

var userObj = '@Model'; 

从Javascript访问MVC的模型属性

3) Using Html.Raw without quotes.

3)使用Html。生没有引号。

   var userObj = @Html.Raw(Model); 

从Javascript访问MVC的模型属性

4) Using Html.Raw along with quotes

4)使用Html。生一起报价

   var userObj = '@Html.Raw(Model)'; 

从Javascript访问MVC的模型属性

The Html.Raw was of no much use for us while assigning a object to variable.

Html。在为变量分配对象时,Raw对我们来说没什么用。

5) Using Json.Encode() without quotes

5)使用Json.Encode()不带引号

var userObj = @Json.Encode(Model); 

//result is like
var userObj = {&quot;Name&quot;:&quot;Raj&quot;,
               &quot;IsAuthenticated&quot;:true,
               &quot;LoginDateTime&quot;:&quot;\/Date(1482572875150)\/&quot;,
               &quot;Age&quot;:26,
               &quot;UserIconHTML&quot;:&quot;\u003ci class=\&quot;fa fa-users\&quot;\u003e\u003c/i\u003e&quot;
              };

We do see some change, We see our Model is being interpreted as a object. But we have those special characters changed into entity names. Also wrapping the above syntax in quotes is of no much use. We simply get the same result within quotes.

我们确实看到了一些变化,我们看到我们的模型被解释为一个对象。但是我们把这些特殊的字符变成了实体名。同样,用引号括住上面的语法也没什么用。我们只是在引号中得到相同的结果。

From the docs of Json.Encode()

从Json.Encode()文档中

Converts a data object to a string that is in the JavaScript Object Notation (JSON) format.

将数据对象转换为JavaScript对象表示法(JSON)格式的字符串。

As you have already encountered this entity Name issue with property assignment and if you remember we overcame it with the use of Html.Raw. So lets try that out. Lets combine Html.Raw and Json.Encode

正如您已经遇到了属性赋值的实体名称问题,如果您还记得我们使用Html.Raw克服了这个问题。我们来试试。结合Html。生和Json.Encode

6) Using Html.Raw and Json.Encode without quotes.

6)使用Html。生和Json。编码没有引号。

var userObj = @Html.Raw(Json.Encode(Model));

Result is a valid Javascript Object

结果是一个有效的Javascript对象

 var userObj = {"Name":"Raj",
     "IsAuthenticated":true,
     "LoginDateTime":"\/Date(1482573224421)\/",
     "Age":26,
     "UserIconHTML":"\u003ci class=\"fa fa-users\"\u003e\u003c/i\u003e"
 };

从Javascript访问MVC的模型属性

7) Using Html.Raw and Json.Encode within quotes.

7)使用Html。生和Json。编码在引号内。

var userObj = '@Html.Raw(Json.Encode(Model))';

从Javascript访问MVC的模型属性

As you see wrapping with quotes gives us a JSON data

如您所见,用引号括起来会得到JSON数据

Conslusion on Object assignment

Conslusion对象赋值

  • Use Html.Raw and Json.Encode in combintaion to assign your object to javascript variable as JavaScript object.
  • 使用Html。生和Json。使用梳状编码将对象作为javascript对象分配给javascript变量。
  • Use Html.Raw and Json.Encode also wrap it within quotes to get a JSON
  • 使用Html。生和Json。Encode还将其封装在引号中以获取JSON

Note: If you have observed the DataTime data format is not right. This is because as said earlier Converts a data object to a string that is in the JavaScript Object Notation (JSON) format and JSON does not contain a date type. Other options to fix this is to add another line of code to handle this type alone using javascipt Date() object

注意:如果您观察到数据格式不正确。这是因为如前所述,将数据对象转换为JavaScript对象表示法(JSON)格式的字符串,而JSON不包含日期类型。解决此问题的其他选项是添加另一行代码,使用javascipt Date()对象单独处理此类型

var userObj.LoginDateTime = new Date('@Html.Raw(Model.LoginDateTime)'); 
//without Json.Encode


How to access Model data in Javascript/Jquery code block in .js file

Razor syntax has no meaning in .js file and hence we cannot directly use our Model insisde a .js file. However there is a workaround.

Razor语法在.js文件中没有任何意义,因此我们不能直接在.js文件中使用我们的模型。然而,有一个变通的办法。

1) Solution is using javascript Global variables.

1)解决方案是使用javascript全局变量。

We have to assign the value to a global scoped javascipt variable and then use this variable within all code block of your .cshtml and .js files. So the syntax would be

我们必须将值分配给全局作用域的javascipt变量,然后在.cshtml和.js文件的所有代码块中使用该变量。语法是

<script type="text/javascript">
  var userObj = @Html.Raw(Json.Encode(Model)); //For javascript object
  var userJsonObj = '@Html.Raw(Json.Encode(Model))'; //For json data
</script>

With this in place we can use the variables userObj and userJsonObj as and when needed.

在适当的位置上,我们可以在需要时使用userObj和userJsonObj变量。

Note: I personally dont suggest using global variables as it gets very hard for maintainance. However if you have no other option then you can use it with having a proper naming convention .. something like userAppDetails_global.

注意:我个人不建议使用全局变量,因为这样很难维护。但是,如果您没有其他选择,那么您可以使用它与一个合适的命名约定。就像userAppDetails_global。

2) Using function() or closure Wrap all the code that is dependent on the model data in a function. And then execute this function from the .cshtml file .

2)使用函数()或闭包来包装所有依赖于函数中模型数据的代码。然后从.cshtml文件执行此函数。

external.js

external.js

 function userDataDependent(userObj){
  //.... related code
 }

.cshtml file

.cshtml文件

 <script type="text/javascript">
  userDataDependent(@Html.Raw(Json.Encode(Model))); //execute the function     
</script>

Note: Your external file must be referenced prior to the above script. Else the userDataDependent function is undefined.

注意:您的外部文件必须在上述脚本之前被引用。另外,userDataDependent函数没有定义。

Also note that the function must be in global scope too. So either solution we have to deal with global scoped players.

还要注意,函数也必须在全局范围内。所以无论哪种解决方案,我们都必须与全球范围内的参与者打交道。

#3


17  

try this: (you missed the single quotes)

试试这个:(你错过了单引号)

var floorplanSettings = '@Html.Raw(Json.Encode(Model.FloorPlanSettings))';

#4


3  

Wrapping the model property around parens worked for me. You still get the same issue with Visual Studio complaining about the semi-colon, but it works.

将模型属性包装在parens上对我很有用。您仍然会遇到Visual Studio抱怨分号的问题,但是它是有效的。

var closedStatusId = @(Model.ClosedStatusId);

#5


0  

If "ReferenceError: Model is not defined" error is raised, then you might try to use the following method:

如果出现“ReferenceError: Model未定义”错误,您可以尝试使用以下方法:

$(document).ready(function () {

    @{  var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
         var json = serializer.Serialize(Model);
    }

    var model = @Html.Raw(json);
    if(model != null && @Html.Raw(json) != "undefined")
    {
        var id= model.Id;
        var mainFloorPlanId = model.MainFloorPlanId ;
        var imageDirectory = model.ImageDirectory ;
        var iconsDirectory = model.IconsDirectory ;
    }
});

Hope this helps...

希望这有助于……