0
我試圖驗證用戶名的唯一性,但由於某些原因,它不能正常工作。我這樣做以下列方式唯一用戶名驗證在ASP.NET MVC4中不起作用
模型
public class System_User
{
public int Id { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
[Remote("doesUserNameExist", "System_User", HttpMethod = "POST", ErrorMessage = "User name already exists. Please enter a different user name.")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
public bool IsAdmin { get; set; }
}
控制器
我加入以下代碼到我的SYSTEM_USER控制器
[HttpPost]
public JsonResult doesUserNameExist(string UserName)
{
var user = Membership.GetUser(UserName);
return Json(user == null);
}
查看 我有默認創建的MVC必要引用生成視圖的jQuery
@model WhiteBoard.Models.System_User
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<table class="userTable">
<tr>
<td>
@Html.LabelFor(model => model.FirstName)
</td>
<td>
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</td>
</tr>
<tr>
<td>
@Html.LabelFor(model => model.LastName)
</td>
<td>
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</td>
</tr>
<tr>
<td>
@Html.LabelFor(model => model.UserName)
</td>
<td>
@Html.EditorFor(model => model.UserName)
@Html.ValidationMessageFor(model => model.UserName)
</td>
</tr>
<tr>
<td>
@Html.LabelFor(model => model.Password)
</td>
<td>
@Html.EditorFor(model => model.Password)
@Html.ValidationMessageFor(model => model.Password)
</td>
</tr>
<tr>
<td>
@Html.LabelFor(model => model.IsAdmin)
</td>
<td>
@Html.EditorFor(model => model.IsAdmin)
@Html.ValidationMessageFor(model => model.IsAdmin)
</td>
</tr>
<tr>
<td colspan="2">
<input class="btn btn-success" type="submit" value="Create User" />
</td>
</tr>
</table>
}
<div>
<p>
@Html.ActionLink("Back to List", "Index")
</p>
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
}
當我運行應用程序,它既不拋出一個異常,也沒有驗證工作。
我可以知道我在哪裏犯了一個錯誤
如果用戶!= null,那麼它總是返回false,並表示用戶名已被使用。當我使用user == null時,正如你所說的那樣,它總是返回true,並且即使它已經被使用也需要用戶名 – DoIt
如果你在斷點檢查用戶返回的是什麼?用戶是否真的存在?這是會員提供商的內部版本還是您自己編寫的內容? – Vulcronos
這是一個內置的成員提供商和用戶總是空答顯然這就是問題所在。 – DoIt