我正在开发一个相当大的 MVC 3 Web 应用程序。在过去的几年里,各种技能各异的程序员都在研究这个问题,因此理解这一切是一个缓慢而令人沮丧的过程。
我目前的主要问题是试图了解以前的工作人员正在尝试使用以下代码做什么:
这是视图CreatePartial
(尽管没有用作局部视图)
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<RetainedAvailability.ViewModels.CreateAccountViewModel>" %>
<script type="text/javascript">
SetupCreateView();
$(document).ready(function () { $('input:submit,button').button(); });
</script>
<h2>Create a New Account</h2>
<p>
Use the form below to create a new account.
</p>
<p>
Passwords are required to be a minimum of <%:ViewData["PasswordLength"]%> characters in length.
</p>
<form id="CreateForm" runat="server">
<%:Html.ValidationSummary(true, "Account creation was unsuccessful. Please correct the errors and try again.")%>
<div>
<fieldset>
<legend>Account Information</legend>
<div class="editor-label">
<%:Html.LabelFor(m => m.User.UserName)%>
</div>
<div class="editor-field">
<%:Html.TextBoxFor(m => m.User.UserName)%>
<%:Html.ValidationMessageFor(m => m.User.UserName)%>
</div>
<%:Html.ValidationMessageFor(m => m.User.Email)%>
<%:Html.HiddenFor(m => m.User.Email)%>
<div class="editor-label">
<%:Html.LabelFor(m => m.User.Password)%>
</div>
<div class="editor-field">
<%:Html.PasswordFor(m => m.User.Password)%>
<%:Html.ValidationMessageFor(m => m.User.Password)%>
</div>
<div class="editor-label">
<%:Html.LabelFor(m => m.User.ConfirmPassword)%>
</div>
<div class="editor-field">
<%:Html.PasswordFor(m => m.User.ConfirmPassword)%>
<%:Html.ValidationMessageFor(m => m.User.ConfirmPassword)%>
</div>
<div class="editor-label">
<%:Html.LabelFor(m => m.User.Role)%>
</div>
<div class="editor-field">
<%:Html.DropDownListFor(m => m.User.Role, Model.Roles)%>
<%:Html.ValidationMessageFor(m => m.User.Role)%>
</div>
<p>
<input type="submit" value="Register" />
</p>
</fieldset>
</div>
</form>
这是相关的控制器方法
[HttpPost]
[Authorize(Roles = "Administrator,StationManager")]
public ActionResult CreatePartial(RegisterModel User)
{
if (ModelState.IsValid)
{
// Attempt to register the user and get status
MembershipCreateStatus createStatus = MembershipService.CreateUser(User.UserName, User.Password, User.Email);
// If successful registration, update the db
if (createStatus == MembershipCreateStatus.Success)
{
// Link role and user
Roles.AddUserToRole(User.UserName, User.Role);
// Link station and user
_repository.LinkUserToStation(User.UserName, (Guid) Session["StationID"]);
// Save tables
_repository.SaveChanges();
// Create success notification
var res = new AjaxResponse<CrewMember>
{
Data = null,
IsSuccess = true,
GrowlNotification = "Created " + User.UserName
};
// Return notification
return new JsonResult {Data = res, JsonRequestBehavior = JsonRequestBehavior.AllowGet};
}
else
{
ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
}
}
// If we got this far, something failed, redisplay form
ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
var Errors = ModelState.Where(e => e.Value.Errors.Any()).Select(ee => ee.Value.Errors.First().ErrorMessage).ToList();
var res1 = new AjaxResponse<dynamic>
{
Data = null,
IsSuccess = false,
Errors =
ModelState.Where(e => e.Value.Errors.Any()).Select(
ee => ee.Value.Errors.First().ErrorMessage).ToList()
};
return new JsonResult {Data = res1, JsonRequestBehavior = JsonRequestBehavior.AllowGet};
}
因此,您可以看到任何模型错误都封装在 a中AjaxResponse
,然后作为 a 传递JsonResult
,我希望将其传递回视图。
问题是一旦视图中的表单与无效数据(这是我正在测试的)一起使用,什么也不会发生。没有错误信息。我假设视图端缺少一些将使用JsonResult
. 视图中的验证类似乎没有被使用。
也没有返回视图,只是JsonResult
, 这对于 ASP.NET MVC 是否可以接受?
编辑
以下 JS 处理表单的验证。尽管视图已经使用了验证实体,但它手动将错误应用于 DOM。只是我还是这是验证表单的一种不必要的冗长方式?
function ShowValidationErrors(data) {
$('#CreateForm input[type=text]').removeClass("ui-state-error");
$('#CreateForm label').css('font-weight', 'normal');
$('.field-validation-error').remove();
for (var i = 0; i < data.Errors.length; i++) {
$('#CreateForm label[for=' + recordName + '_' + data.Errors[i].Target + '], #CreateForm label[for=' + data.Errors[i].Target + ']').css('font-weight', 'bold');
// $('#CreateForm #' + recordName + '_' + data.Errors[i].Target +', #CreateForm #' + data.Errors[i].Target).attr('class', 'input-validation-error');
$('#CreateForm #' + recordName + '_' + data.Errors[i].Target + ', #CreateForm #' + data.Errors[i].Target).addClass("ui-state-error");
$('<p class="field-validation-error">* ' + data.Errors[i].Message + '</p>').insertAfter('#CreateForm #' + recordName + '_' + data.Errors[i].Target);
$('<p class="field-validation-error">* ' + data.Errors[i].Message + '</p>').insertAfter('#CreateForm #' + data.Errors[i].Target);
$('.input-validation-error:first').focus();
}
}