2012-10-03 23 views
6

Tengo dos campos de entrada ocultos en mi formulario:ASP.NET MVC 3 HiddenFor Javascript

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

voy a asignar el valor de la siguiente manera:

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

Puede alguien por favor dígame cómo Puedo eliminar los campos <input> ocultos y reemplazarlos por un @Html.HiddenFor<> y hacer que mi actualización de Javascript sea HiddenFor? Quiero hacer esto porque obviamente vinculará automáticamente los datos.

Mi HiddenFor actualmente se ve algo como esto:

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

cambio el Javascript para hacer esto:

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

me sale el siguiente error en la consola:

Uncaught TypeError: Cannot set property 'value' of null 

¿Alguien puede ver dónde estoy yendo terriblemente mal?

Respuesta

10

Los Id. De estos campos tendrán subrayados, no puntos, sus nombres tendrán los puntos. Pruebe esto:

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

Eso funcionaba perfecto. Muchas muchas gracias. – Subby

3

Su problema es que id será otra. Listing.Location.Latitude es el atributo de nombre.

Por ejemplo:

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

generado como:

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

Muchas gracias – Subby

4

probar esto.

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

Así se puede obtener el elemento con Javascript:

document.getElementById("theIdyouWant") 
+1

Ah. No sabía que podía especificar una identificación como esa. Muchas gracias. – Subby