Alex Zhukovskiy
Alex Zhukovskiy

Reputation: 10015

How to overwrite one model property in ASP.Net core

I have a model with say 10 properties. A, B, C and so on...

Property A is an array.

For each value in array I generate one tag like this:

<div class="col-sm-10 row">
    @foreach (var item in Model.A)
    {
        <div class="col-sm-1 right-buffer">
            <a href="@item.Value"><i class="" aria-hidden="true">@item.Text</i></a>
        </div>
    }
</div>

When user clicks on some link I should redirect it to the same page, but with Some model property changed. For example:

Current url: my/controller/someaction?name=Alex&age=20&from=fr&CurrentA= with model ?name=Alex&age=20&from=fr&CurrentA=

If user clicks on <a> with text foo it should be redirected on my/controller/someaction?name=Alex&age=20&from=fr&CurrentA=foo

then is clicks on <a> with text bar and it should be now redirected on my/controller/someaction?name=Alex&age=20&from=fr&CurrentA=bar

So entire query string (except one parameter) should be preserved to send current model state to server while I want to set one value and redirect it to the same page but with new value.

Eventually, it should acts like postback with one extra value setted to model

Is it possible or I should use JS and perform everything myself?

Upvotes: 1

Views: 1717

Answers (1)

Alex Zhukovskiy
Alex Zhukovskiy

Reputation: 10015

Manually i solved it like this:

First, create hidden fields for every property in model:

<form asp-controller="search" asp-action="index" method="get" role="form" id="searchForm" asp-antiforgery="false">
    <input asp-for="SessionId" type="hidden" name="sessionId" value="@Model.SessionId" />
    <input asp-for="Quantity" type="hidden" name="quantity" value="@Model.Quantity"/>
    <input asp-for="SortField" type="hidden" name="sortField" value="@Model.SortField"/>
    <input asp-for="IsAscending" type="hidden" name="IsAscending" value="@Model.IsAscending" />
    <input asp-for="Offset" type="hidden" name="offset" value="0" />

    ...
</form>

Then, use JS to replace value in hidden field and then submit form. Values from inputs will be autimatically converter in query string, so everything works fine:

function sortDocuments(sortField) {
    var sField = document.getElementById('SortField');
    var isDescending = document.getElementById('IsAscending');
    if (sField.value === sortField) {
        if (isDescending.value.toUpperCase() === 'FALSE') {
            isDescending.value = 'TRUE';
        } else {
            sField.value = 'rank';
            isDescending.value = 'FALSE';
        }
    } else {
        sField.value = sortField;
        isDescending.value = 'FALSE';
    }
    document.getElementById('searchForm').submit();
}

Not very elegant, but it does its job.

Upvotes: 1

Related Questions