C# 从 Javascript 访问 MVC 的模型属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16361364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:50:41  来源:igfitidea点击:

Accessing MVC's model property from Javascript

c#javascriptjqueryasp.net-mvcmodel

提问by Null Reference

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);

采纳答案by Justin Helgerson

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 Encodemethod that property:

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

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

回答by FROgistics

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);

回答by danmbuen

try this: (you missed the single quotes)

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

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

回答by Murat Y?ld?z

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

如果出现“ReferenceError: Model is not defined”错误,那么您可以尝试使用以下方法:

$(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...

希望这可以帮助...

回答by Rajshekar Reddy

Contents of the Answer

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

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

答案的内容

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

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

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

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

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

有两种类型的 c# 变量 ( Model) 赋值给 JavaScript 变量。

  1. Property assignment- Basic datatypes like int, string, DateTime(ex: Model.Name)
  2. Object assignment- Custom or inbuilt classes (ex: Model, Model.UserSettingsObj)
  1. 财产分配-基本数据类型一样intstringDateTime(例如:Model.Name
  2. 对象分配- 自定义或内置类(例如:ModelModel.UserSettingsObj

Lets look into the details of these two assignments.

让我们来看看这两个任务的细节。

For the rest of the answer lets consider the below AppUserModel 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;  

enter image description here

在此处输入图片说明

As you can see there are couple of errors, Rajand Trueis considered to be javascript variables and since they dont exist its an variable undefinederror. Where as for the dateTime varialble the error is unexpected numbernumbers 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的变量,因为他们不存在,它的variable undefined错误。对于 dateTime 变量,错误是unexpected number数字不能包含特殊字符,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'; 

enter image description here

在此处输入图片说明

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

结果是有效的,因此将属性赋值用引号括起来为我们提供了有效的语法。但请注意 NumberAge现在是一个字符串,所以如果你不想要,我们可以删除引号,它将被呈现为数字类型。

3)Using @Html.Rawbut without wrapping it in quotes

3)使用@Html.Raw但不用引号括起来

 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);

enter image description here

在此处输入图片说明

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

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

From the docs Html.Raw()

来自文档Html.Raw()

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

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

But still we have errors in other lines.

但是我们在其他行中仍然有错误。

4)Using @Html.Rawand also wrapping it within quotes

4)使用@Html.Raw并用引号括起来

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)';

enter image description here

在此处输入图片说明

The results are good with all types. But our HTMLdata 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.Rawto interpret your HTML data as is.
  • 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.Raw按原样解释 HTML 数据。
  • 照顾好您的 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; 

enter image description here

在此处输入图片说明

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

当您将 ac# 对象分配给 javascript 变量.ToString()时,将分配该对象的值。于是有了上面的结果。

2Wrapping object assignment in quotes

2用引号包裹对象赋值

var userObj = '@Model'; 

enter image description here

在此处输入图片说明

3)Using Html.Rawwithout quotes.

3)Html.Raw不带引号使用。

   var userObj = @Html.Raw(Model); 

enter image description here

在此处输入图片说明

4)Using Html.Rawalong with quotes

4)使用Html.Raw以及股价

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

enter image description here

在此处输入图片说明

The Html.Rawwas 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.

我们确实看到了一些变化,我们看到我们的模型被解释为一个对象。但是我们把那些特殊字符改成了entity names. 将上述语法用引号括起来也没什么用。我们只是在引号内得到相同的结果。

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 Nameissue with property assignment and if you remember we overcame it with the use of Html.Raw. So lets try that out. Lets combine Html.Rawand Json.Encode

由于您已经在entity Name属性分配中遇到过这个问题,如果您还记得的话,我们使用Html.Raw. 所以让我们试试看。让我们结合Html.RawJson.Encode

6)Using Html.Rawand Json.Encodewithout quotes.

6)使用Html.RawJson.Encode不使用引号。

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"
 };

enter image description here

在此处输入图片说明

7)Using Html.Rawand Json.Encodewithin quotes.

7)在引号内使用Html.RawJson.Encode

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

enter image description here

在此处输入图片说明

As you see wrapping with quotes gives us a JSON data

如您所见,用引号括起来为我们提供了一个JSON 数据

Conslusion on Object assignment

关于对象分配的结论

  • Use Html.Rawand Json.Encodein combintaion to assign your object to javascript variable as JavaScript object.
  • Use Html.Rawand Json.Encodealso wrap it within quotesto get a JSON
  • 使用Html.RawJson.Encode组合将您的对象作为JavaScript 对象分配给 javascript 变量。
  • 使用Html.Raw并将其Json.Encode包装在其中quotes以获取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) formatand JSON does not contain a datetype. Other options to fix this is to add another line of code to handle this type alone using javascipt Date()object

注意:如果您观察到 DataTime 数据格式不正确。这是因为如前所述Converts a data object to a string that is in the JavaScript Object Notation (JSON) format,JSON 不包含date类型。解决此问题的其他选项是添加另一行代码以使用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 .jsfile

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

Razor syntax has no meaning in .jsfile and hence we cannot directly use our Model insisde a .jsfile. 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 .cshtmland .jsfiles. 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 userObjand userJsonObjas and when needed.

有了这个地方,我们可以利用变量userObjuserJsonObj作为并在需要时。

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 closureWrap all the code that is dependent on the model data in a function. And then execute this function from the .cshtmlfile .

2)使用function()closure将所有依赖于模型数据的代码包装在一个函数中。然后从.cshtml文件中执行这个函数。

external.js

external.js

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

.cshtmlfile

.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 userDataDependentfunction 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.

另请注意,该函数也必须在全局范围内。因此,无论是哪种解决方案,我们都必须与全球范围的参与者打交道。

回答by Amer Jamaeen

I know its too late but this solution is working perfect for both .net framework and .net core:

我知道为时已晚,但此解决方案对 .net 框架和 .net 核心都非常有效:

@System.Web.HttpUtility.JavaScriptStringEncode()

@System.Web.HttpUtility.JavaScriptStringEncode()