asp.net-mvc 如何在javascript中传递模型数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18849257/
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-09-08 03:09:50  来源:igfitidea点击:

How to pass model data in javascript

javascriptasp.net-mvc

提问by Optimus

I need to pass a model value item.ID to one of my javascript function how can I do that ?

我需要将模型值 item.ID 传递给我的 javascript 函数之一,我该怎么做?

I triedfunction("@item.ID")but its not working

我试过了,function("@item.ID")但它不工作

采纳答案by DK Chauhan

You can pass the model data into the java script file in these ways (1). Just set the value in hidden field and access the value of hidden field in java script. (2). And pass the value using function parameter. (3).

您可以通过以下方式将模型数据传递到 java 脚本文件中 (1)。只需在隐藏字段中设置值并在java脚本中访问隐藏字段的值。(2). 并使用函数参数传递值。(3).

        var LoginResourceKeyCollection = {
            UserName_Required: '<%= Model.UserName%>',
            Password_Required: '<%= Model.Password%>'

        }
   </script>

回答by Alex

It generally works this way, you just have to omit the ""otherwise it gets interpreted as string. So you can write something like that in your JS:

它通常以这种方式工作,您只需要省略""否则它会被解释为字符串。所以你可以在你的 JS 中写这样的东西:

var myinteger = @item.ID;

which renders as

呈现为

var myinteger = 123;   //for example

Edit: This makes sense when you id is an integer, of course, for strings you need to encapsulate it in ''or "". And don't get annoyed by any syntax errors reported by intellisense, it seems to have a problem with that but it works out just nicely.

编辑:当您 id 是整数时,这是有道理的,当然,对于字符串,您需要将其封装在''or 中""。并且不要对智能感知报告的任何语法错误感到恼火,它似乎有问题,但效果很好。

回答by RollerCosta

Try this...mind single quotes on parameter value while calling js function

试试这个...在调用 js 函数时注意参数值上的单引号

function MyJsFunction(modelvalue)
{
     alert("your model value: " + modelvalue);
}

<input type="button" onclick="MyJsFunction('@item.ID')" />
OR
<input type="button" onclick="MyJsFunction('@(item.ID)')" />

回答by kiransr

The best solution is pass your textbox ID to javascrpit function and then in function retrieve the value form the ID,

最好的解决方案是将您的文本框 ID 传递给 javascrpit 函数,然后在函数中从 ID 中检索值,

 @Html.TextBoxFor(model => model.DatemailedStart, new {id = "MailStartDate", placeholder = "MM/DD/YYYY", maxlength = "40", @class = "TextboxDates", @onblur = "isValidDate('MailStartDate');" })

  function isValidDate(id) {
    var dateString = $('#'+id+'').val();
  }