Hello guys i am working on a projekt where i can add articles to a cart. My cart is a partialview.When i add a Article to my cart the old data isnt stored and only one (the new article) article is added to my cart.
This is the code for the Post in my codebehind Im adding a Postition with RandomNumbers for testing
[BindProperty]
public List<Position> ArticlePositions { get; set; } = new List<Position>();
public PartialViewResult OnPostAddPosition(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 partialViewResult = new PartialViewResult()
{
ViewName = "_ArticlePositonsPartial",
ViewData = new ViewDataDictionary<List<Position>>(ViewData, articlePositions),
};
return partialViewResult;
}
This is my Partialview with the Model:
@model List<Rechnungen.Models.Position>
<div >
<table >
<thead >
<tr>
<th style="width:72.5px" >Anzahl</th>
<th style="width:72.5px" >ID</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr id="">
<td style="width:72.5px" >
<span >@item.ArticleAmount</span>
</td>
<td style="width:72.5px" >
<span >@item.ArticleId</span>
</td>
</tr>
}
</tbody>
</table>
</div>
Where i render the Partial:
<div id="MyPartialView">
@{
await Html.RenderPartialAsync("_ArticlePositonsPartial", Model.ArticlePositions, ViewData);
}
</div>
How i add A Position to cart:
@Html.AntiForgeryToken()
<button onclick="GetPartialView()"><i ></i>Hinzufügen</button>
And this is my Javascript for it:
function GetPartialView() {
$.ajax({
type: "POST",
url: '?handler=AddPosition',
dataType: "html",
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
success: function(data) {
$("#MyPartialView").html(data);
},
error: function(result) {
alert("fail");
}
});
}
My code is working so far, when i add something to my cart my site is looking like this=>
When i click a second time on the add button my site looks like this=>
So my problem is that the Data in ArticlePositions isnt stored. When i Debugg my Code the ArticlePositions are NULL
when the Post Method is called.
CodePudding user response:
HTTP is stateless, so any state created in your OnPostAddPosition
method is destroyed at the end of the request. You have to implement strategies to persist state across requests. There are a number of options available in Razor Pages. You should research them to identify the most suitable one for your application:
https://www.learnrazorpages.com/razor-pages/state-management