ASP.NET MVC 3 HiddenFor Javascript

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

ASP.NET MVC 3 HiddenFor Javascript

javascripthtmlasp.net-mvcrazorhidden-field

提问by Subby

I have two hidden input fields in my form:

我的表单中有两个隐藏的输入字段:

<input type="hidden" name="lat" id="lat" value=""/>
<input type="hidden" name="long" id="long" value="" />

I am assigning their value by doing the following:

我通过执行以下操作来分配它们的价值:

document.getElementById('lat').value = lat;
document.getElementById('long').value = lng;

Can someone please tell me how I can remove the hidden <input>fields and replace them with a @Html.HiddenFor<>and make my Javascript update the HiddenFor? I want to do this because it will obviously automatically bind the data.

有人可以告诉我如何删除隐藏<input>字段并用 a 替换它们@Html.HiddenFor<>并使我的 Javascript 更新 HiddenFor 吗?我想这样做是因为它显然会自动绑定数据。

My HiddenFor currently looks something like this:

我的 HiddenFor 目前看起来像这样:

@Html.HiddenFor(m => Model.Listing.Location.Latitude);
@Html.HiddenFor(m => Model.Listing.Location.Longitude);

I change the Javascript to do this:

我更改 Javascript 以执行此操作:

document.getElementById('Listing.Location.Latitude').value = lat;
document.getElementById('Listing.Location.Longitude').value = lng;

I get the following error in the Console:

我在控制台中收到以下错误:

Uncaught TypeError: Cannot set property 'value' of null 

Can anyone see where I am going horribly wrong?

谁能看到我哪里错了?

回答by dove

The Ids of these fields will have underscores not dots, their names will have the dots. Try this:

这些字段的 ID 将带有下划线而不是点,它们的名称将带有点。试试这个:

document.getElementById('Listing_Location_Latitude').value = lat;

回答by John Hpa

Try this.

试试这个。

@Html.HiddenFor(m => m.Listing.Location.Latitude, new {id = "theIdyouWant"})

So you can get the element using Javascript:

因此,您可以使用 Javascript 获取元素:

document.getElementById("theIdyouWant")

回答by webdeveloper

Your problem is that idwill be another. Listing.Location.Latitudeis name attribute.

你的问题是那id将是另一个。Listing.Location.Latitude是名称属性。

For example:

例如:

@Html.TextBoxFor(x => x.General.Site_Name)

generated as:

生成为:

<input id="General_Site_Name" type="text" name="General.Site_Name" />