obi
obi

Reputation: 31

Getting models variable name in razor editor templates

I would like to use generate IDs depending on the models variable name.

I have two models

public class ConceptViewModel
{
    [AllowHtml]
    public string Content { get; set; }
    [AllowHtml]
    public string EnglishContent { get; set; }
    public string Instructions { get; set; }
}

and

public class InputDataCollectionViewModel
{
    public int Id { get; set; }
    public ConceptModel Definition { get; set; }
    public ConceptModel Publication { get; set; }
    public bool Exist { get; set; }
}

I'm using EditorTemplates for ConceptViewModel:

@model Models.ConceptViewModel

<tr>
    <td>@Html.LabelFor(m => m, htmlAttributes: new { @class = "control-label" })</td>                
    <td hidden>
        @Html.TextBoxFor(m => Content, (@Model.Exist ? null : (object)new { @disabled = "disabled" }))
        @Html.TextBoxFor(m => m.EnglishContent)
    </td>
    <td hidden>@Html.TextBoxFor(m => m.Instructions)</td>   
    <td><button type="button" class="btn btn-default" onclick="openEditor('UNIQUE_NAME_DEPENDING_ON_MODEL_NAME');">Edit</button></td>
</tr>

and the view:

@model Models.InputDataCollectionViewModel    

<div class="container">
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        {
            <div class="form-group">
                @Html.HiddenFor(model => model.Id)
                <table class="table table-hover table-condensed">
                    <tbody>
                        @Html.EditorFor(model => model.Definition)
                        @Html.EditorFor(model => model.Publication)                            
                    </tbody>
                    <tfoot></tfoot>
                </table>

                <div class="row">
                    <div class="col-md-12">
                        <button class="btn btn-default" type="submit">Save</button>
                    </div>
                </div>    
            </div>
        }
    }

which generates html containing:

<label class="control-label" for="Definition">
<input id="Definition_Content" name="Definition.Content" type="text" value="" />
<input id="Definition_EnglishContent" name="Definition.EnglishContent" type="text" value="" />
<input id="Definition_Instructions" name="Definition.Instructions" type="text" value="..." />

and the same for the other ConceptViewModels. So from this I can easily reference it because of the unique IDs (Definition_, Publication_ and so forth for other inputs I have elsewhere).

Now my question is, how would I get the strings containg "Definition", "Publication" so I could use it with the generated buttons. What I want is:

openEditor('Definition');
openEditor('Publication');

in the onclick.

Upvotes: 1

Views: 463

Answers (1)

obi
obi

Reputation: 31

I've managed to find the solution. The Html helper @Html.IdFor(m => m)

Upvotes: 2

Related Questions