简体   繁体   English

.Net Core Razor 页面 - 后不显眼后刷新字段 ajax

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

I have created a.Net Core Razor Pages Application.我创建了一个.Net Core Razor Pages 应用程序。 There are two input fields and a submit button in a razor page. razor 页面中有两个输入字段和一个提交按钮。 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.在 OnGet() 方法中分配了一条消息“Hello World”。

To keep the message, I used unobtrusive ajax.为了保留信息,我使用了不显眼的 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?有没有什么方法可以刷新数字而无需在 ajax 回调方法中编写代码来为每个元素单独分配值?

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.最终,我的目标是发布页面的一部分并在回发时刷新字段中的绑定数据,而不是在 ajax 回调中单独为控件分配值。 Code sample is given below代码示例如下

Note:Need to do this without the whole page relaod.注意:需要在不重新加载整个页面的情况下执行此操作。

Index.cshtml索引.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索引.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.与 ASP.NET WebForms 类似,ASP.NET 核心表单 state 存储在 ModelState 中。 After posting, the form will be loaded with the the binding values, then updated with ModelState.发布后,表单将加载绑定值,然后使用 ModelState 进行更新。 So there is a need to clear the values within ModelState, otherwise the values will be overwritten.所以需要清除ModelState中的值,否则会被覆盖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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