ASP.NET MVC 3 HiddenFor Javascript

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 assign their value by doing the following:

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

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

My HiddenFor currently looks something like this:

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

I am modifying Javascript for this:

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

The following error appears in the console:

 Uncaught TypeError: Cannot set property 'value' of null 

Can anyone see where I am going terribly wrong?

+6
source share
3 answers

Identifiers of these fields will contain underscores, not periods; their names will have periods. Try the following:

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

Try it.

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

So you can get the element using Javascript:

 document.getElementById("theIdyouWant") 
+4
source

Your problem is that id will be different. Listing.Location.Latitude - attribute of the name.

For instance:

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

generated as:

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

Source: https://habr.com/ru/post/926826/


All Articles