2012-10-03 10 views
6

私は私の形で2つの隠し入力フィールドを持っている:ASP.NET MVC 3 HiddenFor Javascriptを

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

私は次の操作を行って、その値を代入しています:

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

を誰かがどのように教えてくださいことができます隠された<input>フィールドを削除して@Html.HiddenFor<>に置き換え、JavascriptをHiddenForに更新できますか?明らかにデータを自動的にバインドするので、これを実行したいと思います。私HiddenForは現在、このようなものになります

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

を私はこれを行うにはJavascriptを変更します。

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

私はコンソールで次のエラーを取得する:

Uncaught TypeError: Cannot set property 'value' of null 

誰かが私がひどく間違って行くのを見ることができますか?

答えて

10

これらのフィールドのIDは、アンダースコアにドットを付けず、名前にドットが付いています。これを試してください:

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

完璧に働きました。本当にありがとう。 – Subby

3

あなたの問題はidは別のものになります。 Listing.Location.Latitudeは名前属性です。例えば

:として生成

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

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

ありがとうございます – Subby

4

はこれを試してみてください。

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

だからあなたはJavascriptを使用して要素を取得することができます

document.getElementById("theIdyouWant") 
+1

ああ。私はそのようなIDを指定することができるか分からなかった。どうもありがとうございました。 – Subby