Razor Pages model value discrepancy after OnPost modifcation

Viewed 391

can somone please help me understand why the page is showing an out of date value for "MyProperty" when using a TagHelper vs a standard input element?

The value is being modified in the OnPost method of a Razor page. After the OnPost the TagHelper input is showing the value that was sent in the post, but the non-tag helper input shows the actual up-to-date value.

Example page model:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace WebApplication1.Pages.Test
{
    public class TestModel : PageModel
    {
        [BindProperty]
        public string MyProperty { get; set; } = null;

        public void OnGet()
        {
            MyProperty = "Default value";
        }

        public PageResult OnPost()
        {
            MyProperty = "Posted value overwritten by some logic";

            return Page();
        }

    }
}

Example razor page:-

@page
@model WebApplication1.Pages.Test.TestModel

<form asp-antiforgery="true">

    <p><input value="@Model.MyProperty" readonly /></p>
    <p><input asp-for="MyProperty" /></p>

    <button type="submit">Post data</button>

</form>

On the initial page load (OnGet) the values are the same, but if you hit the submit button to trigger a post, the values rendered in each input are different?

1 Answers

I have flagged as duplicate. I found an answer in ASP.NET Core: asp-* attributes use request payload over model?. The asp-for attributes use the ModelState dictionary to render the values, and not the Model that was passed to the view. This can be resolved by calling ModelState.Clear() before returning the page view.

Related