简体   繁体   English

如何将模型字段传递给视图中的Javascript函数?

[英]How to pass a model field to a Javascript function in a view?

I have a simple question that has been vexing me tonight... I have an ASP.NET MVC4 + Razor application. 我有一个简单的问题,今晚让我感到烦恼......我有一个ASP.NET MVC4 + Razor应用程序。 When the user clicks a radio button, I want to pass a string value from a field in the model, "Timezone", to the onclick handler, which is a javascript function. 当用户单击单选按钮时,我想将模型中的字段“Timezone”中的字符串值传递给onclick处理程序,这是一个javascript函数。 In the javascript function, I will take the string and do some work, but for now, I simply pop-up an alert(). 在javascript函数中,我将接受字符串并做一些工作,但是现在,我只是弹出一个alert()。 I have found a lot of references to having to do special quoting, and I've tried all of them, but no matter what I do, the alert shows nothing, but the form that has the radio button shows me a valid value in its Timezone textbox. 我找到了很多关于必须进行特殊引用的引用,并且我已经尝试了所有这些,但无论我做什么,警报都没有显示任何内容,但是带有单选按钮的表单显示了我的有效值时区文本框。

I would really appreciate your help to figure out what I am doing wrong... If this is not possible (why?), then can I access the model's value from the javascript function? 我真的很感谢你的帮助,弄清楚我做错了什么......如果这不可能(为什么?),那么我可以从javascript函数访问模型的值吗? I tried @model.Timezone, but always have an empty string. 我试过@ model.Timezone,但总是有一个空字符串。 Really vexing stuff when I know that it must be something really easy! 当我知道它一定是非常简单的东西时真的很烦人! Anyway, here is the code for the radio button and the simple javascript function. 无论如何,这里是单选按钮和简单的javascript函数的代码。 I'd really appreciate your help! 我真的很感谢你的帮助!

Thanks, Mike 谢谢,迈克

    @Html.RadioButtonFor(model => model.TimezoneSource, "C",
        new {propertyName = "UpdateTimezoneRadioButton", 
            onClick = "TimezoneClicked(@model.Timezone)" })Update Timezone

function TimezoneClicked(timezone) {
    alert(timezone);
}

You shouldn't be doing 你不应该这样做

  onClick = "TimezoneClicked(@model.Timezone)" 

when you use that within the html helper function, it gets treated as a normal string. 当你在html帮助函数中使用它时,它被视为普通字符串。 Instead you should be doing the following: 相反,你应该做以下事情:

onClick = "TimezoneClicked('" + Model.Timezone + "')"

This will pass the Timzone value in the object to the function. 这会将对象中的Timzone值传递给函数。 If it's still empty, try to print it out like the following to make sure the property is not empty. 如果它仍然是空的,请尝试将其打印出来,如下所示,以确保该属性不为空。

<span> @Model.Timezone </span>

You can try the below code: 您可以尝试以下代码:

@Html.RadioButtonFor(model => model.TimezoneSource, "C",
    new {propertyName = "UpdateTimezoneRadioButton", 
        onClick = "TimezoneClicked('" + Model.Timezone + "')" })Update Timezone

function TimezoneClicked(timezone) {
alert(timezone);
}

如果你需要获得函数中的任何dom元素,你可以这样做:

 document.getElementById('@Html.IdFor(model => model.Draw)') 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM