2

I have a Razor View which has a section where the user can add new rows for ad-hoc opening/closing times on specific dates. It consists of three controls - a DatePicker, two Select lists and a "delete row" button. Existing saved rows are rendered on page-load through Razor, and any new rows are added via an OnClick event and JavaScript appending largely fixed html to the DOM element. All rows are then saved (or removed as required) on HTTPPost.

I have a new requirement which requires implementation of a much more complicated data-set for these ad-hoc, "user-generated" rows. The HTML for each of these rows is extensive. Is there a more elegant way of injecting Razor within a View on a button click than appending hard-coded HTML in JavaScript?

  • Use the `BeginCollectionItem()` helper - for and example refer [this Q/A](http://stackoverflow.com/questions/40539321/partial-view-passing-a-collection-using-the-html-begincollectionitem-helper/40541892#40541892) –  Nov 24 '17 at 11:12

1 Answers1

0

This depends entirely on your use case, and you did not provide any code in your question, but there's something called Partial View. You can read a basic introduction here.

For your case, I'd do something like this:

Controller

public IActionResult GetNewRow()
{
    return PartialView("_NewRow");
}

View

<button id="btnAddRow" class="btn btn-primary">Add new row</button>

<script type="application/javascript">
    $(function() {
        $("#btnAddRow").on("click", function () {
            $.get("/GetNewRow", function success(data) {
                $("#WHEREVERYOUAREADDINGROWS").append(data);
            });
        });
    });
</script>

PartialView (_NewRow)

<tr>
    <td>Add whatever you need here</td>
<tr>

Note: I didn't try this so the AJAX syntax might be a little off.

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120