M Kenyon II
M Kenyon II

Reputation: 4254

JavaScript in MVC Editor template doesn't render properly

I'm moving some controls from a view to an Editor. In my Editor I have this HiddenFor:

@Html.HiddenFor(m => m.EmailDataVariables)

I have some javascript that tries to read it (this works in my original page, but not in the view):

var myValue = document.getElementById('EmailDataVariables').value;

The HiddenFor renders out like this (which breaks the above JavaScript):

<input id="EmailTemplate_EmailDataVariables" 
    name="EmailTemplate.EmailDataVariables" 
    type="hidden" 
    value="myData">

Should I just assume the control will always be named EmailTemplate.EmailDataVariables and write my javascript like this:

var myValue = document.getElementById('EmailTemplate.EmailDataVariables').value;

Or is there a better way to handle this?

Upvotes: 0

Views: 122

Answers (1)

Mike Cluck
Mike Cluck

Reputation: 32511

You have two options.

1) Assume the ID will always be EmailTemplate_EmailDataVariables and update your JS accordingly.

2) Give it a unique ID that you will always know.

@Html.HiddenFor(m => m.EmailDataVariables, new {id = "EmailDataVariables"})

Source

Upvotes: 2

Related Questions