问题描述
我需要将一页的各个部分分成部分视图,并且其中一部分包含一个提交数据的表格。我一直在处理这个问题,并且设法在不重新加载页面的情况下提交了表单。
但是我有两个问题:
- 成功发布后不会清除表单字段
- 如果验证失败,则返回结果时这些验证消息不会出现。
我承认我对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>
控制器(HomeController)
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,并且可以正常加载。请任何人能建议我要去哪里错了吗?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)