我希望能够通过从MVC表单执行Ajax帖子来显示验证错误。所有的服务器验证工作正常,但是当我使用ajax帖子发布时,我无法让页面显示任何验证错误。我已经查看了stackoverflow上的其他答案,但它们似乎令人费解,似乎这个问题必须已经解决了数千次。
这是我的c#服务器侧视图模型:
public class Card_TextViewModel:IValidatableObject
{
[Key]
[Required]
[StringLength(15, MinimumLength = 2)]
[Display(Name = "Product Code")]
[DataType(DataType.Text)]
public string Prod_Code { get; set; }
[Required]
[DataType(DataType.MultilineText)]
[Display(Name = "Page 1 Text")]
public string Page1Text { get; set; }
[Required]
[DataType(DataType.MultilineText)]
[Display(Name = "Inside Text")]
public string InsideText { get; set; }
[Display(Name = "User Name")]
[DataType(DataType.Text)]
public string UserName { get; set; }
[Display(Name = "Export Date")]
public DateTime? ExportDate { get; set; }
public IList<Card_Text> Card_Text { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if(!string.IsNullOrEmpty(Prod_Code))
{
if(string.IsNullOrWhiteSpace(Prod_Code.Substring(0,1)))
{
yield return new ValidationResult("The product code cannot start with a space", new[] { "Prod_Code" });
}
}
}
}
这是我的api代码:
public async Task<ActionResult> CreateAddExtra([Bind(Include = "Prod_Code,Page1Text,InsideText")] Card_TextViewModel viewModel)
{
try
{
if (!Request.IsAjaxRequest())
return Json(new { success = false, message = "Request ajax request only" });
if (!ModelState.IsValid)
return Json(new { success = false, message = "Invalid data" });
Card_Text card_Text = await db.Card_Text.FindAsync(viewModel.Prod_Code);
if (card_Text != null)
return Json(new { success = false, message = string.Format("The product code {0} already exists", viewModel.Prod_Code) });
card_Text = Mapper.Map<Card_TextViewModel, Card_Text>(viewModel);
card_Text.UserName = User.Identity.Name;
db.Card_Text.Add(card_Text);
if (await db.SaveChangesAsync() == 0)
return Json(new { success = true, message = string.Format("Error creating product code {0}", viewModel.Prod_Code) });
return Json(new { success = true });
}
catch (Exception exp)
{
}
return Json(new { success = false });
}
以上所有工作正常并没有问题,这里是发布到CreateAddExtra()的javascript
(function () {
$(document).ready(function () {
var successCount = 0;
var addCreate = function () {
var url = "https://localhost:44393/Card_Text/CreateAddExtra";
var data = $("#create").serialize();
$.post(url, data)
.done(function (data, textStatus, jqXHR) {
if (data.success === true) {
successCount++;
$('#successCount').text(successCount);
} else {
$.validator.unobtrusive.parse(document);
/*would like the unobtrusive javascript to display any valide errors that occurred on the post back, which are store in MVC ModelState
How do we activate unobtrusive javascript?
*/
}
});
return false;
};
//just event for a button press
$("#add").click(addCreate);
});
})();
这是MVC html页面代码:
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "create" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<hr />
<div class="form-group">
@Html.LabelFor(model => model.Prod_Code)
@Html.EditorFor(model => model.Prod_Code, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Prod_Code, "", new { @class = "text-danger" })
</div>
<div class="form-group">
@Html.LabelFor(model => model.Page1Text)
@Html.EditorFor(model => model.Page1Text, new { htmlAttributes = new { @class = "form-control", rows = 10, columns = 40 } })
@Html.ValidationMessageFor(model => model.Page1Text, "", new { @class = "text-danger" })
</div>
<div class="form-group">
@Html.LabelFor(model => model.InsideText)
@Html.EditorFor(model => model.InsideText, new { htmlAttributes = new { @class = "form-control", rows = 10, columns = 40 } })
@Html.ValidationMessageFor(model => model.InsideText, "", new { @class = "text-danger" })
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
<input type="submit" id="add" value="Add" class="btn btn-primary" />
@Html.ActionLink("Back to List", "Index", "Card_Text", null, new { id = "recordCount", @class = "btn btn-default" })
</div>
<div>
<span>Records added:</span>
<span id="successCount" class="text-danger">0</span>
</div>
}
因此,如果在回发后发生错误更改错误,我如何激活不显眼的javascript以向用户显示错误?
感谢您的时间
答案 0 :(得分:1)
我从这个link获得了这个片段,它显示了一种处理ajax调用中模型状态错误的简单技巧。
$(function () {
// hijax the form
$("form").submit(function (e) {
var $form = $(this);
var validator = $form.data("validator");
if (!validator || !$form.valid())
return;
e.preventDefault();
$.ajax({
url: "@Url.Action("index")",
type: "POST",
data: $form.serialize(),
statusCode: {
400: function(xhr, status, err) {
var errors = $.parseJSON(err);
validator.showErrors(errors);
}
},
success: function() {
// just reload the page for now
location.reload(true);
}
});
});
});