Nik Volk
Nik Volk

Reputation: 47

How to store identical html blocks in a project correctly? I want to use the same block in different views

I have a block that opens modally for selection from a list. I don't want to embed it in every view. I want this to happen through Razor or C#. I think it would be wrong to store this in _Layout.cshtml (I could be wrong).

<label hidden id="selectionInitiator"></label>
<label hidden id="sourceList"></label>
<div id="modalDialog" class="modal fade">
    <div id="dialogContent" class="modal-dialog">
        <div style="background:white; padding:15px; border-radius:5px;">
            <div class="modal-header">
                <button class="close" data-dismiss="modal" area-hidden="true">X</button>
                <h4>Выберите элемент из списка</h4>
            </div>
            <div id="modalContainer" class="modal-body">
                <div class="treeItems" id="treeRoot">
                    <!-- Dymanical -->
                    Загрузка данных...

                </div>
            </div>
        </div>
    </div>
</div>

Upvotes: 0

Views: 34

Answers (1)

Md Rahatur Rahman
Md Rahatur Rahman

Reputation: 3244

This type of reusable code for modal boxes should be in the _Layout.cshtml file. Otherwise you will have to remember and add in all the pages where you need the modal box.

However if you do not want to put the html in the _Layout.cshtml file then you have to include it in all the views where you need those. For that you can do the followings:

  • Move the html to a partial view, call it _ModalBox.cshtml
  • Include the partial view in all the pages where you need that
  • Use javascript to hide/show the modal (I guess you are already doing that)

First Move the view to a partial file called _ModalBox.cshtml. Keep this file in the Shared folder.

Then include the view in the pages like this:

@await Html.PartialAsync("_ModalBox.cshtml")

Note: You can add the _ModalBox.cshtml partial view to the _Layout.cshtml file instead. That would be the better practice.

Upvotes: 1

Related Questions