简体   繁体   中英

Add part of HTML code by jquery

I use ASP.NET MVC application and has the following code:

<div id="divComments">
    @foreach (var comment in Model.Comments) {
        <div id="comment-@comment.ID">
            <div>
                @comment.Username<br />
                @comment.DateAdded.ToString()
            </div>
            <div>
                @comment.Comment
            </div>
            <input type="button" class="deleteComment" value="Del" id="btnDel-@comment.ID" />
            <br />
        </div>
    }
</div>

Also, I want to add div block with id="comment-X" via jquery. I do it the following way:

 $('#divComments').append('<div id="comment-' + resp.Result.ID + '"><div>' + $('#Username').val() + '<br />' + resp.Result.date + '</div><div>' + comment + '</div><input type="button" class="deleteComment" value="Del" id="btnDel-' + resp.Result.ID + '" /><br /></div>');

Is it possible to move it to any PartialView/Html file and work with it in both places - cshtml (inside my foreach) and jquery? This HTML part is only an example; this part can be much more bigger.

The first section is fine, if you want to move to a partial view you can have the partial view setup the html you want with a viewmodel passing in the information you want populated. You would then call that controller action and then append the result to the divComments block.

This would allow you to add complicated pieces of html without a messy string, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM