ASP 核心 Ajax 从部分发布

ASP Core Ajax Posting From Partials

我需要将一页的各个部分分成部分视图,其中一个部分包含用于提交数据的表单。我一直在研究这个问题,并设法在不重新加载页面的情况下提交表单。

但是我有两个问题:

我承认我一开始对 ASP 中的 AJAX 不太熟悉,但希望有人可以希望。这是我的代码:

型号

using System.ComponentModel.DataAnnotations;

namespace MVCValidation.Models
{
    public class Thing
    {
        public int Id { get; set; }
        
        [Required]
        public string Value { get; set; }
        public string OtherValue { get; set; }
    }
}

主视图 (_Index.cshtml)

@model MVCValidation.Models.Thing

@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Ajax Partial Test</h1>
</div>

<div class="row">
    <div class="col">
        <form asp-controller="Home" asp-action="Edit" data-ajax="true" data-ajax-method="POST">
            @await Html.PartialAsync("_Form", Model)
        </form>
    </div>
</div>

局部视图 (_Form.cshtml)

@model MVCValidation.Models.Thing

@Html.AntiForgeryToken()

<div class="form-horizontal">
    @Html.ValidationSummary(true, "", new {@class = "text-danger"})
    @Html.HiddenFor(m => m.Id)
    <div class="form-group">
        @Html.LabelFor(m => m.Value, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(m => m.Value, new {htmlAttributes = new { @class = "form-control" }})
            @Html.ValidationMessageFor(m => m.Value, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="submit" class="btn btn-success"/>
        </div>
    </div>
</div>

控制器(家庭控制器)

namespace MVCValidation.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public Thing GetThing()
        {
            return new Thing(){Id = 1, OtherValue = "Other"};
        }

        public IActionResult Index()
        {
            
            return View(GetThing());
        }

        [ValidateAntiForgeryToken]
        [HttpPost]
        public IActionResult Edit(Thing thing)
        {
            if(ModelState.IsValid)
            {
                ModelState.Clear();
                return PartialView("_Form", GetThing());
            }
            
            return PartialView("_Form", thing);
        }
    }
}

在我的 _Layout 视图中,我引用了 jquery.unobtrusive-ajax.min.js 并且加载正常。请问有人能指出我哪里出错了吗?

所以,我最终找到了这篇文章:https://damienbod.com/2018/11/09/asp-net-core-mvc-ajax-form-requests-using-jquery-unobtrusive/ 并看到了我做错了什么。

我将标签扩展为如下所示:

<form asp-controller="Home" asp-action="Edit" 
   data-ajax="true" 
   data-ajax-method="POST"
   data-ajax-mode="replace"
   data-ajax-update="#result">
      <div id="result">
         @await Html.PartialAsync("_Form", Model)
      </div>
</form>

PartialAsync 调用现在发生在 div 中,最终将成为填充结果的目标...因此它有效地替换了自身。

我还必须将控制器方法更改为:

[ValidateAntiForgeryToken]
[HttpPost]
public IActionResult Edit(Thing thing)
{
     if(ModelState.IsValid)
     {
          return RedirectToAction(nameof(Index));
     }
            
     return PartialView("_Form", thing);
}

这正确returns模型无效时的部分视图,如果有效则允许再次使用该页面。