我正在使用 jquery 对话框来显示我添加和修改问题的视图的详细信息
我能够显示表单,并且在更新按钮上,第一级验证工作正常,[Required]
和[RegularExpression(...)]
,但它不适用于模型验证级别({{1 }},模型返回错误,但表单没有显示它们。
这是我正在使用的IValidatableObject
控制器
jQuery
模型
[HttpPost]
public ActionResult _Degree(TDegree degree)
{
if (ModelState.IsValid)
{
if (degree.Degree == 0)
{
db.TDegrees.Add(degree);
db.SaveChanges();
}
else
{
TryUpdateModel<TDegree>(degree);
}
return RedirectToAction("Index", "Profile");
}
// what should i return here to stay on the dialog form + returning the errors? i tried this way to show the errors but the errors not shown as html but string
return Content(ShowAllErrors());
}
private String ShowAllErrors()
{
StringBuilder sb = new StringBuilder();
TagBuilder ul = new TagBuilder("ul");
foreach (var e in ModelState.Values.Where(t => t.Errors.Count > 0))
{
foreach (var d in e.Errors)
{
TagBuilder li = new TagBuilder("li");
li.MergeAttribute("class", "field-validation-error");
li.SetInnerText(d.ErrorMessage);
sb.Append(li.ToString());
}
}
ul.SetInnerText(sb.ToString());
return ul.ToString();
}
索引视图
public partial class TDegree : IValidatableObject
{
// Primitive properties
public long Degree { get; set; }
public int Country { get; set; }
public long Applicant { get; set; }
[DisplayName("Degree Type")]
public short DegreeType { get; set; }
[Required]
public string Major { get; set; }
[Required]
public string Institution { get; set; }
[DisplayName("Completion Year")]
public short CompletionYear { get; set; }
[RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "Email is not valid")]
public string Email { get; set; }
[DataType(DataType.PhoneNumber)]
public string Phone { get; set; }
public bool IsEducation { get; set; }
// Navigation properties
public virtual TApplicant TApplicant { get; set; }
public virtual TCountry TCountry { get; set; }
public virtual TDegreeType TDegreeType { get; set; }
// this method is running after the attributes validations and its returning the errors correctly but they are not shown on the form!!
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (DegreeType == 0)
yield return new ValidationResult("Degree Type is required", new string[] { "DegreeType" });
if (CompletionYear < 1950 || CompletionYear > DateTime.Today.Year)
yield return new ValidationResult("Completion Year is out of range!", new string[] { "CompletionYear" });
}
}
详细信息视图(局部视图)
@Html.ImageLink("_Degree", "Profile", new { id = 0 }, @Url.Content("~/Content/images/add.png"), "Add", new { @class = "addLink" }, null)
<table>
<tr>
<th>
Country
</th>
<th>
Type
</th>
<th>
Major
</th>
<th>
Institution
</th>
<th>
Year
</th>
<th>
Email
</th>
<th>
Phone
</th>
<th>
</th>
</tr>
@foreach (var item in Model)
{
<tr class="row">
<td>
@Html.DisplayFor(modelItem => item.TCountry.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.TDegreeType.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Major)
</td>
<td>
@Html.DisplayFor(modelItem => item.Institution)
</td>
<td>
@Html.DisplayFor(modelItem => item.CompletionYear)
</td>
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
<td>
@Html.DisplayFor(modelItem => item.Phone)
</td>
<td>
@Html.ImageLink("_Degree", "Profile", new { id = item.Degree }, @Url.Content("~/Content/images/select.png"), "Edit", new { @class = "editLink" }, null)
</td>
</tr>
}
</table>
<div id="updateDialog" title="Degree Details">
</div>
<script type="text/javascript">
var linkObj;
$(function () {
$('#updateDialog').dialog({
autoOpen: false,
width: 590,
resizable: false,
modal: true,
buttons: {
"Update": function () {
$("#update-message").html('');
$("#updateDegreeForm").validate();
$("#updateDegreeForm").submit();
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
$(".editLink,.addLink").click(function () {
linkObj = $(this);
var dialogDiv = $('#updateDialog');
var viewUrl = linkObj.attr('href');
$.get(viewUrl, function (data) {
dialogDiv.html(data);
var $form = $("#updateDegreeForm");
$form.unbind();
$form.data("validator", null);
$.validator.unobtrusive.parse(document);
$form.validate($form.data("unobtrusiveValidation").options);
dialogDiv.dialog('open');
});
return false;
});
});
function updateSuccess() {
if ($("#update-message").html() == "False") {
$("#update-message").css('display', 'block');
// here it working fine if the model attributes fired the errors
}
else {
// if the model attributes validations was correct and the model validation returned errors, this block will be executed
// i need here to show the errors of the model, and if there was no errors i will close the dialog
}
}
</script>
如何让对话框中显示所有级别的验证? 提前谢谢
答案 0 :(得分:1)
在浪费了差不多2天后,我偶然发现了解决问题的方法。我用于partial / jquery对话框的框架与您使用的相同(我从博客文章中获取)。我修改了我的Create
方法,如下所示:
[HttpPost]
public JsonResult Create(EventObject evt)
{
if(ModelState.IsValid)
{
//save the model and return success
return new JsonResult{
Data = new
{
Result="S",
Message="successfully created event"
}
};
}
else
{
return new JsonResult{
Data = new
{
Result="E",
Message=CONVERT MODELSTATE TO STRING
}
};
}
}
现在在标记方面,我有以下div:
<div id="create-event-error"></div>
我的更新功能如下:
function updateSuccess(a) {
if (a.Result=="S") {
$("#update-message").html(a.Message).show().delay(3000).hide();
$dlg.dialog('close');
}
else {
var d=$("div#create-event-errors");
d.html(a.Message).dialog({
//VARIOUS DIALOG OPTIONS
});
}
}
取代对话,您可以随意显示错误。