ASP.NET MVC 3 HiddenFor Javascript

Sub*_*bby 7 html javascript asp.net-mvc hidden-field razor

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

<input type="hidden" name="lat" id="lat" value=""/>
<input type="hidden" name="long" id="long" value="" />
Run Code Online (Sandbox Code Playgroud)

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

document.getElementById('lat').value = lat;
document.getElementById('long').value = lng;
Run Code Online (Sandbox Code Playgroud)

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

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

@Html.HiddenFor(m => Model.Listing.Location.Latitude);
@Html.HiddenFor(m => Model.Listing.Location.Longitude);
Run Code Online (Sandbox Code Playgroud)

我更改Javascript来执行此操作:

document.getElementById('Listing.Location.Latitude').value = lat;
document.getElementById('Listing.Location.Longitude').value = lng;
Run Code Online (Sandbox Code Playgroud)

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

Uncaught TypeError: Cannot set property 'value' of null 
Run Code Online (Sandbox Code Playgroud)

任何人都可以看到我可怕的错误吗?

dov*_*ove 11

这些字段的ID会有下划线而不是点,它们的名字会有点.试试这个:

document.getElementById('Listing_Location_Latitude').value = lat;
Run Code Online (Sandbox Code Playgroud)


Joh*_*Hpa 5

尝试这个。

@Html.HiddenFor(m => m.Listing.Location.Latitude, new {id = "theIdyouWant"})
Run Code Online (Sandbox Code Playgroud)

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

document.getElementById("theIdyouWant")
Run Code Online (Sandbox Code Playgroud)