2012-10-03 3 views
6

Ho due campi di input nascosti in mia forma:ASP.NET MVC 3 HiddenFor Javascript

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

Sto assegnando loro valore effettuando le seguenti operazioni:

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

qualcuno può dirmi come Posso rimuovere i campi nascosti <input> e sostituirli con uno @Html.HiddenFor<> e rendere il mio Javascript aggiornare HiddenFor? Voglio farlo perché ovviamente vincolerà automaticamente i dati.

mio HiddenFor attualmente sembra qualcosa di simile:

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

posso cambiare il Javascript per fare questo:

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

ottengo il seguente errore nella console:

Uncaught TypeError: Cannot set property 'value' of null 

Qualcuno può vedere dove sto andando terribilmente male?

risposta

10

Gli ID di questi campi avranno caratteri di sottolineatura non punti, i loro nomi avranno i punti. Prova questo:

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

che ha funzionato perfetto. Grazie mille. – Subby

3

Il tuo problema è che id sarà un altro. Listing.Location.Latitude è l'attributo nome.

Ad esempio:

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

generato come:

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

Grazie mille – Subby

4

Prova questa.

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

Così si può ottenere l'elemento utilizzando Javascript:

document.getElementById("theIdyouWant") 
+1

Ah. Non sapevo di poter specificare un id come quello. Grazie mille. – Subby