I want to be able to display some text, but also have the text be modifiable via jQuery.
<%= Html.DisplayFor(model => model.DeviceComponentName)%>
If I used EditorFor instead of DisplayFor I would see an ID for the input control. I do not want the value to be editable in that way, though. So, I have made it a DisplayFor, but it does not generate an ID property for the element.
Should I just wrap the DisplayFor in a div and do something like:
<div id="<%= ViewData.TemplateInfo.GetFullHtmlFieldName("DeviceComponentName") %>">
<%= Html.DisplayFor(model => model.DeviceComponentName)%>
</div>
$('#DeviceComponentName').text('newValue');
Or is there a cleaner way of achieving this?
Update: Is there a way which doesn’t depend on hard-coded strings? Something that ties to the object itself so if my property name changes I’d get a compile error?
Also, I am using this code, but I do not see an ID value appear:
<td class="editableValue">
<%--Label should be editable, so it needs an ID, but only will be edited by jQuery so it can't be an EditorFor--%>
<%= Html.DisplayFor(model => model.DeviceComponentName, new { id = "DeviceComponentName" })%>
<button type="button" id="ComponentTreeButton" class="nestedDialogButton">...</button>
</td>
To avoid ‘magic string’ inputs (in case your model properties change), you could do this with an extension. It also makes for much cleaner code:
Then simply use it like this:
Will produce
Or if you want it to be wrapped in a span:
Which will make:
Non-Razor
For non Razor syntax, you simply use it like this:
and: