我正在使用ASP.Net MVC 4和ADO.net(不是EF)开发用户注册系统。
我的BAL / BLL图层中有这个方法:
public static void InsertMemberUsername(RegisterRequest register, Guid id_fk)
{
if (Exist(register.UserName.Username))
{
// display error message to pick some other username
}
MEMBER_USERNAME entityToCreate = CreateMemberUsername(register, id_fk);
MEMBER_USERNAME_DAL.SQLAtlInsert(entityToCreate, "Server=ConnSting Here;");
}
在我的控制器中我有这个:
[CaptchaMvc.Attributes.CaptchaVerify("Captcha is not valid")]
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterRequest model)
{
if (ModelState.IsValid)
{
Membership_BAL.Register(model);
// TODO: Redirect user to profile page
return RedirectToAction("Index", "Home");
}
TempData["Message"] = "Error: captcha is not valid.";
return View();
}
在Register方法内部调用InsertMemberName方法。
如果已经使用了用户名,最好显示错误消息?
答案 0 :(得分:2)
显然有各种方法可以实现这一目标。
从
修改您的功能public static void InsertMemberUsername(RegisterRequest register, Guid id_fk)
{
if (Exist(register.UserName.Username))
{
// display error message to pick some other username
}
MEMBER_USERNAME entityToCreate = CreateMemberUsername(register, id_fk);
MEMBER_USERNAME_DAL.SQLAtlInsert(entityToCreate, "Server=ConnSting Here;");
}
到
public static bool InsertMemberUsername(RegisterRequest register, Guid id_fk)
{
if (Exist(register.UserName.Username))
{
return false;
}
MEMBER_USERNAME entityToCreate = CreateMemberUsername(register, id_fk);
MEMBER_USERNAME_DAL.SQLAtlInsert(entityToCreate, "Server=ConnSting Here;");
return true;
}
我更喜欢在我的模型中有一个表示错误消息的参数,而不是使用TempData。像
这样的东西public class SomeModel
{
public string ErrorMessage { get; set; }
// Your other model parameters go here.
}
然后您可以像这样设置模型中的参数
var someModel = new SomeModel();
if(!InsertMemberUsername( // You parameters))
{
someModel.ErrorMessage = "Error: captcha is not valid.";
}
并将此模型传递给您的视图
return View(someModel);
在视图中,您现在可以显示此参数的内容,例如
<div>
@if(!string.IsNullOrEmpty(@Model.ErrorMessage))
{
@Model.ErrorMessage
}
</div>