简体   繁体   中英

.Net Core Razor Pages - Refresh fields after post -unobtrusive ajax

I have created a.Net Core Razor Pages Application. There are two input fields and a submit button in a razor page. When I click on the button, the numbers in the input fields needs to be incremented. There is a message 'Hello World' which is assigned in the OnGet() method.

To keep the message, I used unobtrusive ajax. In this case, the message will remain there but the numbers will not increment. Is there any way to refresh the numbers without writing code in ajax call back method to assign values individually to each element?

Ultimately, my aim is to post a portion of a page and refresh the bind data in the fields on post back without assigning values to the controls individually in ajax call back. Code sample is given below

Note:Need to do this without the whole page relaod.

Index.cshtml

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}


<h1>@Model.Message</h1>

<form  method="post" data-ajax="true" data-ajax-method="post" >
    <div>
        <input type="text" asp-for="Num1" />
        <input type="text" asp-for="Num2" />
      

        <input type="submit" value="Submit" />

    </div>

   
</form>

Index.cshtml.cs

  public class IndexModel : PageModel
    {
        [BindProperty]
        public int Num1 { get; set; } = 0;
        [BindProperty]
        public int Num2 { get; set; } = 0;
        public string Message { get; set; }

        public void OnGet()
        {
            Message = "Hello World";
            GetNumbers();
        }


        void GetNumbers()
        {
            Num1 += 1;
            Num2 += 5;

        }

        public IActionResult OnPost()
        {
     
            GetNumbers();
            return Page();
        }

    }
ModelState.Remove("Nmu1");
ModelState.Remove("Nmu2");

Similarly to ASP.NET WebForms, ASP.NET Core form state is stored in ModelState. After posting, the form will be loaded with the the binding values, then updated with ModelState. So there is a need to clear the values within ModelState, otherwise the values will be overwritten.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM