0

Hello guys i wanted to ask if there is a way to reload a single partial after a is clicked instead of loading the whole site new.

My site looks like this. Page when i load it for the first time

My code

This is how i load my partialview when i go to my main site.

        <div>
            @{
                await Html.RenderPartialAsync("_ArticlePositonsPartial",Model.ArticlePositions, ViewData);
            }
        </div>

Model for the partial

model IList<Rechnungen.Models.Position>

Partial html

<form enctype="multipart/form-data">
<div class="tableFixHead">
    <table class="table table-striped text-center table-sm " id="tablepost">
        <thead class="table-dark ">
            <tr>
                <th style="width:72.5px" class="">Anzahl</th>
                <th style="width:72.5px" class="">Einheit</th>
                <th style="width:320px" class="">Nr + Bezeichnung</th>
                <th style="width:135px" class="">Stk Preis.</th>
                <th style="width:135px" class="">Ges Preis.</th>
                <th style="width:75px" class=""></th>
            </tr>
        </thead>
        <tbody id="tablebodypost">
            @foreach (var item in Model)
            {
                  <tr id="">
                    <td style="width:72.5px" class="pt-2 ">
                        <span class="TBarticleAmount">@item.ArticleAmount</span>
                    </td>
                    <td style="width:72.5px" class="pt-2 ">
                        <span class="TBarticleType">@item.ArticleId</span>
                    </td>
                    <td style="width:320px; font-size:12px;" class="pt-2 ">
                        <span class="TBarticleNumberAndName">test</span>
                    </td>
                    <td style="width:135px" class="pt-2 ">
                        <span class="TBarticlePrice">test </span>
                    </td>
                    <td style="width:135px;" class="pt-2 ">
                        <span class="TBarticleAmountPrice"> test</span>
                    </td>
                    <td style="width:75px" class=" ">
                        <a class="btn btn-outline-dark btn-sm delete-record" data-id="1" data-toggleToolTip="tooltip" data-placement="top" title="Entfernen">
                            <i class="fa-solid fa-trash-can"></i>
                        </a>
                    </td>
                </tr>
            }
              
            
        </tbody>
    </table>
</div>

So after i Click on the button "Hinzufügen" i want to add something to a list and reload the tablePartial

  <form mmethod="post" asp-page-handler="AddPosition">
                        <button class="btn btn-outline-secondary add-record" type="submit" data-added="0"><i class="fa-solid fa-plus"></i>Hinzufügen</button>
  </form>

Method in codebehind:

  public PartialViewResult OnPostAddPosition()
    {
        ArticlePositions.Add(new Position { ArticleAmount = 1, ArticleId = 2 });
        return new PartialViewResult
        {
            ViewName = "_ArticlePositonsPartial",
            ViewData = new ViewDataDictionary<IList<Position>>(ViewData, ArticlePositions),
           
        };
    }

After the PostMethod is called my site looks like this: Page after calling the PostMethod

I have looked it up in the interned already and found nothing that helped me. Is there a way to only reload the TablePartial?

Yiyi You
  • 16,875
  • 1
  • 10
  • 22
flomue99
  • 87
  • 9

2 Answers2

1

Try to remove form and use button to call js function,and use ajax to call handler,here is a demo:

cshtml:

<div id="MyPartialView">
    @{
        await Html.RenderPartialAsync("_ArticlePositonsPartial", Model.ArticlePositions, ViewData);
    }
</div>
@Html.AntiForgeryToken()
<button class="btn btn-outline-secondary add-record"data-added="0" onclick="GetPartialView()"><i class="fa-solid fa-plus"></i>Hinzufügen</button>

js:

function GetPartialView() {
            $.ajax({
                type: "POST",
                url: '?handler=AddPosition',
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                success: function (data) {
                    $("#MyPartialView").html(data);
                },
                error: function (result) {
                    alert("fail");
                }
            })
        }

Update:

js:

function GetPartialView() {
            $.ajax({
                type: "POST",
                url: '?handler=AddPosition',
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                success: function (data) {
                    document.getElementById("MyPartialView").innerHTML = document.getElementById("MyPartialView").innerHTML + data;
                },
                error: function (result) {
                    alert("fail");
                }
            })
        }
Yiyi You
  • 16,875
  • 1
  • 10
  • 22
  • Yiyi You, Thank you for youzr help. Now the rendering works, but when i click for a second time on >the button> "Hinzufügen" my method OnPostAddpostion() isn't adding a second Position. I Debugged it and the Positions List is always NULL when i call the function. – flomue99 May 20 '22 at 06:13
  • 1
    `he Positions List is always NULL`It depends on what you returned in `OnPostAddPosition()`.What is the `ViewData` in your `OnPostAddPosition()`? – Yiyi You May 20 '22 at 07:00
  • I posted my code again. When i click the button its overriding the old Position – flomue99 May 20 '22 at 07:45
  • Yes,it will replace the old partial view. – Yiyi You May 23 '22 at 01:10
  • Yes. is there a way to store the old Postitions and display all of them? – flomue99 May 23 '22 at 05:57
  • Hello,I have updated the js in my answer,and when click the button,it will keep the old partial view,and add the new partial view into the `
    `.
    – Yiyi You May 23 '22 at 06:27
  • This works, but the Data isnt stored in my codebehind file. – flomue99 May 23 '22 at 06:54
  • Yes,it will only change the html,if you want to save the old data,you need to pass the old data in the form with hidden inputs. – Yiyi You May 23 '22 at 07:05
  • Pass it into the partial or in the oder Page? – flomue99 May 23 '22 at 07:36
  • Pass to OnPostAddPosition,and return all the data to partial view. – Yiyi You May 23 '22 at 07:38
  • Can you send me a code example for this? i dont understand it ..:( – flomue99 May 23 '22 at 07:43
0

I have changed the code:

[BindProperty]
public List<Position> ArticlePositions { get; set; } = new List<Position>();

 public PartialViewResult OnPostAddPosition([FromBody] List<Position> articlePositions)
    {
        Random myObject = new Random();
        Random myObject1 = new Random();

        articlePositions.Add(new Position
        {
            ArticleAmount = myObject1.Next(10, 100),
            ArticleId = myObject.Next(10, 100)
        });
        var data = new NewInvoiceModel(_AddressRepository, _InvoiceNumberRangeRepository, _AddressTelephoneRepository, _ArticleRepository, _ITextsRepository, _HeaderDataRepository);
        data.ArticlePositions = articlePositions;
        var myViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { { "_ArticlePositonsPartial", articlePositions } };
        myViewData.Model = data;
        return new PartialViewResult
        {
            ViewName = "_ArticlePositonsPartial",
            ViewData = myViewData,

        };
    }

HTML:`

<div id="MyPartialView">
 @{
   await Html.RenderPartialAsync("_ArticlePositonsPartial", Model, ViewData);
 }
</div>`

Javascript:

function GetPartialView() {

        var model = @Json.Serialize(Model.ArticlePositions);
        $.ajax({
            type: "POST",
            url: '?handler=AddPosition',
            data: JSON.stringify(model),
            dataType: "html",
            contentType: "application/json",
            headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
            success: function(data) {
                $("#MyPartialView").html(data);
            },
            error: function(result) {
                alert("fail");
            }
        });
    }
flomue99
  • 87
  • 9